<?php
require_once '../includes/auth.php';
require_once '../db.php';

// Admin and staff only
if (!in_array($_SESSION['user_role'] ?? '', ['admin', 'staff'])) {
    header('Location: ../dashboard.php');
    exit;
}

$client_id = intval($_GET['client_id'] ?? $_POST['client_id'] ?? 0);
if (!$client_id) {
    header('Location: index.php');
    exit;
}

// Load client info
$cRes = $conn->query("SELECT id, name, phone, company_id FROM clients WHERE id = $client_id LIMIT 1");
if (!$cRes || $cRes->num_rows === 0) {
    header('Location: index.php');
    exit;
}
$client = $cRes->fetch_assoc();

$errors = [];
$formData = [
    'payment_date'  => date('Y-m-d'),
    'amount'        => '',
    'payment_mode'  => 'Cash',
    'reference_no'  => '',
    'notes'         => '',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData['payment_date'] = $_POST['payment_date'] ?? date('Y-m-d');
    $formData['amount']       = $_POST['amount'] ?? '';
    $formData['payment_mode'] = $_POST['payment_mode'] ?? 'Cash';
    $formData['reference_no'] = trim($_POST['reference_no'] ?? '');
    $formData['notes']        = trim($_POST['notes'] ?? '');

    // Validation
    if (empty($formData['payment_date'])) {
        $errors[] = 'Receipt date is required.';
    }
    $amount = floatval($formData['amount']);
    if ($amount <= 0) {
        $errors[] = 'Amount must be greater than 0.';
    }

    if (empty($errors)) {
        $payDate  = $conn->real_escape_string($formData['payment_date']);
        $payMode  = $conn->real_escape_string($formData['payment_mode']);
        $refNo    = $conn->real_escape_string($formData['reference_no']);
        $notes    = $conn->real_escape_string($formData['notes']);
        $compId   = (int)$client['company_id'];

        $conn->query("
            INSERT INTO client_payments (client_id, company_id, payment_date, amount, payment_mode, reference_no, notes)
            VALUES ($client_id, $compId, '$payDate', $amount, '$payMode', '$refNo', '$notes')
        ");

        if ($conn->affected_rows > 0) {
            header("Location: view.php?client_id=$client_id");
            exit;
        } else {
            $errors[] = 'Failed to save receipt. Please try again.';
        }
    }
}

require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>

<div class="page-header">
    <h2>
        <i class="fas fa-hand-holding-usd" style="color:var(--primary);margin-right:8px;"></i>
        Record Receipt &mdash; <?= htmlspecialchars($client['name']) ?>
    </h2>
    <a href="view.php?client_id=<?= $client_id ?>" class="btn btn-secondary">
        <i class="fas fa-arrow-left"></i> Back to Ledger
    </a>
</div>

<?php if (!empty($errors)): ?>
<div style="background:#fef2f2;border:1px solid #fca5a5;border-radius:8px;padding:12px 16px;margin-bottom:16px;">
    <strong style="color:var(--danger);"><i class="fas fa-exclamation-circle"></i> Please fix the following:</strong>
    <ul style="margin:6px 0 0 16px;color:var(--danger);">
        <?php foreach ($errors as $e): ?>
        <li><?= htmlspecialchars($e) ?></li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

<div class="panel" style="max-width:560px;">
    <div class="panel-header">
        <span class="panel-title"><i class="fas fa-file-invoice-dollar"></i> Receipt Details</span>
    </div>
    <div class="panel-body" style="padding:24px;">

        <!-- Client Info -->
        <div style="background:var(--content-bg);border-radius:8px;padding:12px 16px;margin-bottom:20px;border:1px solid var(--border);">
            <div style="font-size:11px;font-weight:600;text-transform:uppercase;color:var(--text-muted);letter-spacing:.05em;margin-bottom:4px;">Client</div>
            <div style="font-size:16px;font-weight:700;color:var(--text-primary);"><?= htmlspecialchars($client['name']) ?></div>
            <?php if ($client['phone']): ?>
            <div style="font-size:12px;color:var(--text-secondary);margin-top:2px;"><i class="fas fa-phone" style="margin-right:4px;"></i><?= htmlspecialchars($client['phone']) ?></div>
            <?php endif; ?>
        </div>

        <div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:6px;padding:8px 12px;margin-bottom:16px;font-size:12px;color:#1d4ed8;">
            <i class="fas fa-info-circle" style="margin-right:4px;"></i>
            Recording money <strong>received from</strong> this client.
        </div>

        <form method="post">
            <input type="hidden" name="client_id" value="<?= $client_id ?>">

            <div style="margin-bottom:16px;">
                <label style="display:block;font-size:13px;font-weight:600;color:var(--text-secondary);margin-bottom:6px;">
                    Receipt Date <span style="color:var(--danger);">*</span>
                </label>
                <input type="date" name="payment_date"
                       value="<?= htmlspecialchars($formData['payment_date']) ?>"
                       style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;font-family:var(--font);"
                       required>
            </div>

            <div style="margin-bottom:16px;">
                <label style="display:block;font-size:13px;font-weight:600;color:var(--text-secondary);margin-bottom:6px;">
                    Amount Received (&#8377;) <span style="color:var(--danger);">*</span>
                </label>
                <input type="number" name="amount" step="0.01" min="0.01"
                       value="<?= htmlspecialchars($formData['amount']) ?>"
                       placeholder="0.00"
                       style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;font-family:var(--font);"
                       required>
            </div>

            <div style="margin-bottom:16px;">
                <label style="display:block;font-size:13px;font-weight:600;color:var(--text-secondary);margin-bottom:6px;">
                    Payment Mode
                </label>
                <select name="payment_mode"
                        style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;font-family:var(--font);">
                    <?php foreach (['Cash','UPI','Bank Transfer','Cheque'] as $mode): ?>
                    <option value="<?= $mode ?>" <?= $formData['payment_mode'] === $mode ? 'selected' : '' ?>>
                        <?= $mode ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div style="margin-bottom:16px;">
                <label style="display:block;font-size:13px;font-weight:600;color:var(--text-secondary);margin-bottom:6px;">
                    Reference No / Transaction ID
                </label>
                <input type="text" name="reference_no"
                       value="<?= htmlspecialchars($formData['reference_no']) ?>"
                       placeholder="Optional reference number"
                       style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;font-family:var(--font);">
            </div>

            <div style="margin-bottom:24px;">
                <label style="display:block;font-size:13px;font-weight:600;color:var(--text-secondary);margin-bottom:6px;">
                    Notes
                </label>
                <textarea name="notes" rows="3"
                          placeholder="Optional notes..."
                          style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;font-family:var(--font);resize:vertical;"><?= htmlspecialchars($formData['notes']) ?></textarea>
            </div>

            <div style="display:flex;gap:10px;">
                <button type="submit" class="btn btn-success">
                    <i class="fas fa-save"></i> Save Receipt
                </button>
                <a href="view.php?client_id=<?= $client_id ?>" class="btn btn-secondary">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>
