<?php
$active = 'vendors';
$pageTitle = 'Vendor KYC & Approval';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

$id = (int)($_GET['id'] ?? 0);
if (!$id) { echo "<div class='alert alert-danger'>Vendor id required</div>"; require_once __DIR__.'/partials/bottom.php'; exit; }

$stmt = $pdo->prepare("SELECT v.*, k.* FROM vendors v LEFT JOIN vendor_kyc k ON k.vendor_id=v.id WHERE v.id=?");
$stmt->execute([$id]);
$row = $stmt->fetch();
if (!$row) { echo "<div class='alert alert-danger'>Vendor not found</div>"; require_once __DIR__.'/partials/bottom.php'; exit; }

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Manual wallet credit
  if (isset($_POST['add_credit'])) {
    $amount = (int)($_POST['credit_amount'] ?? 0);
    $desc = trim($_POST['credit_description'] ?? 'Manual credit by admin');
    if ($amount > 0) {
      $pdo->beginTransaction();
      try {
        $stmt = $pdo->prepare("UPDATE vendors SET wallet_balance = wallet_balance + ? WHERE id=?");
        $stmt->execute([$amount, $id]);
        $stmt = $pdo->prepare("INSERT INTO wallet_transactions (vendor_id, type, amount, description, ref_type) VALUES (?, 'credit', ?, ?, 'manual')");
        $stmt->execute([$id, $amount, $desc ?: 'Manual credit by admin']);
        $pdo->commit();
        $success = "Added ₹" . number_format($amount) . " to vendor wallet.";
      } catch (Exception $e) {
        $pdo->rollBack();
        $error = $e->getMessage();
      }
    } else {
      $error = 'Amount must be greater than 0.';
    }
  }

  if (!isset($_POST['add_credit'])) {
    $approval_status = $_POST['approval_status'] ?? $row['approval_status'];
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $kyc_status = $_POST['kyc_status'] ?? ($row['status'] ?? 'not_submitted');
    $admin_notes = trim($_POST['admin_notes'] ?? '');

    $pdo->beginTransaction();
    $stmt = $pdo->prepare("UPDATE vendors SET approval_status=?, is_active=?, kyc_status=? WHERE id=?");
    $stmt->execute([$approval_status, $is_active, $kyc_status, $id]);
    $stmt = $pdo->prepare("UPDATE vendor_kyc SET status=?, admin_notes=?, reviewed_at=NOW() WHERE vendor_id=?");
    $stmt->execute([$kyc_status, $admin_notes, $id]);
    $pdo->commit();
    $success = 'Updated successfully.';
  }

  // reload
  $stmt = $pdo->prepare("SELECT v.*, k.* FROM vendors v LEFT JOIN vendor_kyc k ON k.vendor_id=v.id WHERE v.id=?");
  $stmt->execute([$id]);
  $row = $stmt->fetch();
}

function badge($status) {
  $map = ['approved'=>'success','pending'=>'warning','rejected'=>'danger','submitted'=>'warning','not_submitted'=>'secondary'];
  $c = $map[$status] ?? 'secondary';
  return "<span class='badge text-bg-$c'>$status</span>";
}

$docs = [
  'Aadhaar Front' => $row['aadhar_front_path'] ?? null,
  'Aadhaar Back' => $row['aadhar_back_path'] ?? null,
  'PAN Front' => $row['pan_front_path'] ?? null,
  'PAN Back' => $row['pan_back_path'] ?? null,
  'License Photo' => $row['license_photo_path'] ?? null,
];

?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="fw-bold mb-0">Vendor: <?php echo htmlspecialchars($row['vendor_code']); ?> — <?php echo htmlspecialchars($row['name']); ?></h4>
    <div class="text-muted small">Review documents, add approval notes, and activate vendor access.</div>
  </div>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-dark" href="vendor_form.php?id=<?php echo (int)$id; ?>">Edit Vendor</a>
    <a class="btn btn-outline-dark" href="vendors.php">Back</a>
  </div>
</div>

<?php if ($success): ?><div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

<div class="row g-3">
  <div class="col-lg-4">
    <div class="card p-3">
      <div class="fw-semibold mb-2">Vendor Info</div>
      <div class="small text-muted">Phone</div>
      <div class="mb-2"><?php echo htmlspecialchars($row['phone']); ?></div>
      <div class="small text-muted">Email</div>
      <div class="mb-2"><?php echo htmlspecialchars($row['email'] ?? '-'); ?></div>
      <div class="small text-muted">License Number</div>
      <div class="mb-2"><?php echo htmlspecialchars($row['license_number'] ?? $row['license_number'] ?? '-'); ?></div>
      <div class="small text-muted">Category</div>
      <div class="mb-2"><?php echo htmlspecialchars($row['category_name'] ?? '-'); ?></div>
      <div class="d-flex gap-2 mt-2">
        <div><?php echo badge($row['approval_status']); ?></div>
        <div><?php echo badge($row['kyc_status']); ?></div>
        <?php if ((int)$row['is_active']===1) echo "<div><span class='badge text-bg-dark'>active</span></div>"; ?>
      </div>
      <hr>
      <div class="fw-semibold">Wallet</div>
      <div class="fs-4 fw-bold">₹<?php echo (int)$row['wallet_balance']; ?></div>
      <div class="text-muted small">Total earnings: ₹<?php echo (int)$row['total_earnings']; ?> • Jobs: <?php echo (int)$row['total_jobs']; ?></div>
      <button type="button" class="btn btn-sm btn-outline-success mt-2" data-bs-toggle="modal" data-bs-target="#addCreditModal">+ Add Credit</button>
      <hr>
      <div class="fw-semibold small">Withdrawal Details</div>
      <div class="small text-muted">Mode: <?php echo htmlspecialchars($row['withdrawal_payment_mode'] ?? '-'); ?></div>
      <div class="small text-muted">UPI: <?php echo htmlspecialchars($row['withdrawal_upi_id'] ?? '-'); ?></div>
      <?php if (!empty($row['withdrawal_bank_details'])): ?><div class="small text-muted">Bank: <?php echo htmlspecialchars($row['withdrawal_bank_details']); ?></div><?php endif; ?>
      <?php if (!empty($row['expo_push_token'])): ?><div class="small text-muted mt-1">Push: <?php echo htmlspecialchars(substr($row['expo_push_token'], 0, 30)); ?>...</div><?php endif; ?>
    </div>
  </div>

  <div class="col-lg-8">
    <div class="card p-3">
      <div class="fw-semibold mb-2">KYC Documents</div>
      <div class="row g-2">
        <?php foreach ($docs as $label=>$path): ?>
          <div class="col-md-4">
            <div class="border rounded-3 p-2 bg-white h-100">
              <div class="small text-muted"><?php echo htmlspecialchars($label); ?></div>
              <?php if ($path): ?>
                <a href="../<?php echo htmlspecialchars($path); ?>" target="_blank">
                  <img src="../<?php echo htmlspecialchars($path); ?>" class="img-fluid rounded-2 mt-1" alt="<?php echo htmlspecialchars($label); ?>">
                </a>
              <?php else: ?>
                <div class="text-muted small mt-2">Not uploaded</div>
              <?php endif; ?>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
      <hr>
      <form method="post">
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">Vendor Approval</label>
            <select class="form-select" name="approval_status">
              <?php foreach (['pending','approved','rejected'] as $s): ?>
                <option value="<?php echo $s; ?>" <?php if ($row['approval_status']===$s) echo 'selected'; ?>><?php echo $s; ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-md-4">
            <label class="form-label">KYC Status</label>
            <select class="form-select" name="kyc_status">
              <?php foreach (['not_submitted','submitted','approved','rejected'] as $s): ?>
                <option value="<?php echo $s; ?>" <?php if (($row['status'] ?? $row['kyc_status'])===$s) echo 'selected'; ?>><?php echo $s; ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-md-4 d-flex align-items-end">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="is_active" id="activeChk" <?php if ((int)$row['is_active']===1) echo 'checked'; ?>>
              <label class="form-check-label" for="activeChk">Active Access</label>
              <div class="text-muted small">If checked, vendor can use app.</div>
            </div>
          </div>

          <div class="col-12">
            <label class="form-label">KYC Approval Notes (Editable)</label>
            <textarea class="form-control" name="admin_notes" rows="4" placeholder="Write notes for vendor..."><?php echo htmlspecialchars($row['admin_notes'] ?? ''); ?></textarea>
            <div class="text-muted small mt-1">These notes can be shown to vendor in future UI, or used internally.</div>
          </div>

          <div class="col-12 d-flex gap-2">
            <button class="btn btn-dark" type="submit">Save Review</button>
            <a class="btn btn-outline-dark" href="transactions.php?vendor_id=<?php echo (int)$id; ?>">View Transactions</a>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="addCreditModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Add Wallet Credit</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form method="post">
        <div class="modal-body">
          <input type="hidden" name="add_credit" value="1">
          <div class="mb-3"><label class="form-label">Amount (₹)</label><input type="number" name="credit_amount" class="form-control" min="1" required></div>
          <div class="mb-3"><label class="form-label">Description (optional)</label><input type="text" name="credit_description" class="form-control" placeholder="e.g. Bonus, Adjustment"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-success">Add Credit</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
