<?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;
}

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

// Load vendor info
$vRes = $conn->query("SELECT id, name, phone, company_id FROM vendors WHERE id = $vendor_id LIMIT 1");
if (!$vRes || $vRes->num_rows === 0) {
    header('Location: index.php');
    exit;
}
$vendor = $vRes->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[] = 'Payment 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)$vendor['company_id'];

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

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

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

<div class="page-header">
    <h2>
        <i class="fas fa-money-bill-wave" style="color:var(--primary);margin-right:8px;"></i>
        Add Payment &mdash; <?= htmlspecialchars($vendor['name']) ?>
    </h2>
    <a href="view.php?vendor_id=<?= $vendor_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> Payment Details</span>
    </div>
    <div class="panel-body" style="padding:24px;">

        <!-- Vendor 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;">Vendor</div>
            <div style="font-size:16px;font-weight:700;color:var(--text-primary);"><?= htmlspecialchars($vendor['name']) ?></div>
            <?php if ($vendor['phone']): ?>
            <div style="font-size:12px;color:var(--text-secondary);margin-top:2px;"><i class="fas fa-phone" style="margin-right:4px;"></i><?= htmlspecialchars($vendor['phone']) ?></div>
            <?php endif; ?>
        </div>

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

            <div style="margin-bottom:16px;">
                <label style="display:block;font-size:13px;font-weight:600;color:var(--text-secondary);margin-bottom:6px;">
                    Payment 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 (&#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 / Cheque No
                </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 Payment
                </button>
                <a href="view.php?vendor_id=<?= $vendor_id ?>" class="btn btn-secondary">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>
        </form>
    </div>
</div>

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