<?php
$id = (int)($_GET['id'] ?? 0);
$active = 'vendors';
$pageTitle = $id ? 'Edit Vendor' : 'Create Vendor';
require_once __DIR__ . '/partials/top.php';
$pdo = db();
$vendor = null;
if ($id) {
  $stmt = $pdo->prepare("SELECT * FROM vendors WHERE id=?");
  $stmt->execute([$id]);
  $vendor = $stmt->fetch();
  if (!$vendor) { echo "<div class='alert alert-danger'>Vendor not found</div>"; require_once __DIR__.'/partials/bottom.php'; exit; }
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $vendor_code = trim($_POST['vendor_code'] ?? '');
  $name = trim($_POST['name'] ?? '');
  $phone = trim($_POST['phone'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $rating = (float)($_POST['rating'] ?? 4.5);
  $license_number = trim($_POST['license_number'] ?? '');
  $approval_status = $_POST['approval_status'] ?? 'pending';
  $kyc_status = $_POST['kyc_status'] ?? 'not_submitted';
  $is_active = isset($_POST['is_active']) ? 1 : 0;
  $wallet_balance = (int)($_POST['wallet_balance'] ?? 0);
  $category_id = (int)($_POST['category_id'] ?? 0);
  $category_name = trim($_POST['category_name'] ?? '');
  // Derive category_name from categories master when category_id is set
  if ($category_id > 0 && $category_name === '') {
    $st = $pdo->prepare("SELECT name FROM categories WHERE id=?");
    $st->execute([$category_id]);
    $category_name = $st->fetch()['name'] ?? '';
  }
  if ($category_id === 0) $category_name = '';

  if ($vendor_code==='' || $name==='' || $phone==='') {
    $error = 'Vendor code, name, and phone are required.';
  } else {
    // uniqueness checks
    if ($id) {
      $stmt = $pdo->prepare("SELECT id FROM vendors WHERE (vendor_code=? OR phone=? OR email=?) AND id<>? LIMIT 1");
      $stmt->execute([$vendor_code, $phone, $email, $id]);
    } else {
      $stmt = $pdo->prepare("SELECT id FROM vendors WHERE vendor_code=? OR phone=? OR email=? LIMIT 1");
      $stmt->execute([$vendor_code, $phone, $email]);
    }
    if ($stmt->fetch()) {
      $error = 'Vendor code / phone / email must be unique.';
    } else {
      if ($id) {
        $stmt = $pdo->prepare("UPDATE vendors SET vendor_code=?, name=?, phone=?, email=?, rating=?, license_number=?, approval_status=?, kyc_status=?, is_active=?, wallet_balance=?, category_id=?, category_name=? WHERE id=?");
        $stmt->execute([$vendor_code,$name,$phone,$email,$rating,$license_number,$approval_status,$kyc_status,$is_active,$wallet_balance,$category_id,$category_name,$id]);
        $success = 'Vendor updated.';
      } else {
        $stmt = $pdo->prepare("INSERT INTO vendors (vendor_code,name,phone,email,rating,license_number,approval_status,kyc_status,is_active,wallet_balance,category_id,category_name) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
        $stmt->execute([$vendor_code,$name,$phone,$email,$rating,$license_number,$approval_status,$kyc_status,$is_active,$wallet_balance,$category_id,$category_name]);
        $newId = (int)$pdo->lastInsertId();
        $pdo->prepare("INSERT INTO vendor_kyc (vendor_id, status) VALUES (?,?)")->execute([$newId, $kyc_status]);
        $success = 'Vendor created.';
        $id = $newId;
      }
      // reload
      $stmt = $pdo->prepare("SELECT * FROM vendors WHERE id=?");
      $stmt->execute([$id]);
      $vendor = $stmt->fetch();
    }
  }
}

$categories = $pdo->query("SELECT id, name FROM categories ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
if (!$vendor) {
  // default vendor_code suggestion
  $next = $pdo->query("SELECT IFNULL(MAX(id),0)+1 AS next_id FROM vendors")->fetch()['next_id'];
  $suggest = 'VEN' . str_pad((string)$next, 3, '0', STR_PAD_LEFT);
  $vendor = [
    'vendor_code'=>$suggest,'name'=>'','phone'=>'','email'=>'','rating'=>4.5,'license_number'=>'',
    'approval_status'=>'pending','kyc_status'=>'not_submitted','is_active'=>0,'wallet_balance'=>0,
    'category_id'=>0,'category_name'=>''
  ];
}
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="fw-bold mb-0"><?php echo $id ? 'Edit Vendor' : 'Create Vendor'; ?></h4>
    <div class="text-muted small">Manage vendor profile, approvals, and wallet settings.</div>
  </div>
  <a class="btn btn-outline-dark" href="vendors.php">Back</a>
</div>

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

<div class="card p-4">
  <form method="post">
    <div class="row g-3">
      <div class="col-md-4">
        <label class="form-label">Vendor Code</label>
        <input class="form-control" name="vendor_code" required value="<?php echo htmlspecialchars($vendor['vendor_code']); ?>">
      </div>
      <div class="col-md-8">
        <label class="form-label">Name</label>
        <input class="form-control" name="name" required value="<?php echo htmlspecialchars($vendor['name']); ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">Phone</label>
        <input class="form-control" name="phone" required value="<?php echo htmlspecialchars($vendor['phone']); ?>">
      </div>
      <div class="col-md-8">
        <label class="form-label">Email</label>
        <input class="form-control" name="email" value="<?php echo htmlspecialchars($vendor['email'] ?? ''); ?>">
      </div>

      <div class="col-md-4">
        <label class="form-label">Rating</label>
        <input class="form-control" name="rating" type="number" step="0.1" min="0" max="5" value="<?php echo htmlspecialchars((string)$vendor['rating']); ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">Category</label>
        <select class="form-select" name="category_id">
          <option value="0">— Select Category —</option>
          <?php foreach ($categories as $c): ?>
          <option value="<?php echo (int)$c['id']; ?>" <?php echo ((int)($vendor['category_id']??0))===(int)$c['id']?'selected':''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
          <?php endforeach; ?>
        </select>
        <div class="form-text">From categories master</div>
      </div>
      <div class="col-md-8">
        <label class="form-label">License Number</label>
        <input class="form-control" name="license_number" value="<?php echo htmlspecialchars($vendor['license_number'] ?? ''); ?>">
      </div>

      <div class="col-md-4">
        <label class="form-label">Approval Status</label>
        <select class="form-select" name="approval_status">
          <?php foreach (['pending','approved','rejected'] as $s): ?>
            <option value="<?php echo $s; ?>" <?php if ($vendor['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 ($vendor['kyc_status']===$s) echo 'selected'; ?>><?php echo $s; ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">Wallet Balance</label>
        <input class="form-control" name="wallet_balance" type="number" min="0" value="<?php echo (int)$vendor['wallet_balance']; ?>">
      </div>

      <div class="col-12">
        <div class="form-check">
          <input class="form-check-input" type="checkbox" name="is_active" id="activeChk" <?php if ((int)$vendor['is_active']===1) echo 'checked'; ?>>
          <label class="form-check-label" for="activeChk">Vendor Active (can access app)</label>
        </div>
      </div>

      <div class="col-12 d-flex gap-2">
        <button class="btn btn-dark" type="submit"><?php echo $id ? 'Save Changes' : 'Create Vendor'; ?></button>
        <?php if ($id): ?>
          <a class="btn btn-outline-dark" href="vendor_view.php?id=<?php echo (int)$id; ?>">Review KYC</a>
        <?php endif; ?>
      </div>
    </div>
  </form>
</div>

<?php require_once __DIR__ . '/partials/bottom.php'; ?>
