<?php
$active = 'coupons';
$pageTitle = 'Coupon Codes';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

try {
  $pdo->query("SELECT 1 FROM coupon_codes LIMIT 1");
} catch (Exception $e) {
  echo "<div class='alert alert-warning'>Coupon table not found. Run <code>database/coupon_codes.sql</code> to add coupon support.</div>";
  require_once __DIR__ . '/partials/bottom.php';
  exit;
}

$action = $_GET['action'] ?? '';
$id = (int)($_GET['id'] ?? 0);
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $mode = $_POST['mode'] ?? '';
  if ($mode === 'save') {
    $coupon_id = (int)($_POST['coupon_id'] ?? 0);
    $code = strtoupper(trim($_POST['code'] ?? ''));
    $discount_type = $_POST['discount_type'] ?? 'fixed';
    $discount_value = (int)($_POST['discount_value'] ?? 0);
    $min_amount = (int)($_POST['min_amount'] ?? 0);
    $max_uses = trim($_POST['max_uses'] ?? '') === '' ? null : (int)$_POST['max_uses'];
    $valid_from = trim($_POST['valid_from'] ?? '') ?: null;
    $valid_to = trim($_POST['valid_to'] ?? '') ?: null;
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    if ($code === '' || $discount_value <= 0) {
      $msg = "<div class='alert alert-danger'>Code and discount value are required.</div>";
    } elseif ($discount_type === 'percentage' && $discount_value > 100) {
      $msg = "<div class='alert alert-danger'>Percentage cannot exceed 100.</div>";
    } else {
      $stmt = $pdo->prepare("SELECT id FROM coupon_codes WHERE code=? AND id<>?");
      $stmt->execute([$code, $coupon_id]);
      if ($stmt->fetch()) {
        $msg = "<div class='alert alert-danger'>Coupon code already exists.</div>";
      } else {
        if ($coupon_id) {
          $stmt = $pdo->prepare("UPDATE coupon_codes SET code=?, discount_type=?, discount_value=?, min_amount=?, max_uses=?, valid_from=?, valid_to=?, is_active=? WHERE id=?");
          $stmt->execute([$code, $discount_type, $discount_value, $min_amount, $max_uses, $valid_from, $valid_to, $is_active, $coupon_id]);
          $msg = "<div class='alert alert-success'>Coupon updated.</div>";
        } else {
          $stmt = $pdo->prepare("INSERT INTO coupon_codes (code, discount_type, discount_value, min_amount, max_uses, valid_from, valid_to, is_active) VALUES (?,?,?,?,?,?,?,?)");
          $stmt->execute([$code, $discount_type, $discount_value, $min_amount, $max_uses, $valid_from, $valid_to, $is_active]);
          $msg = "<div class='alert alert-success'>Coupon created.</div>";
        }
        $action = '';
        $id = 0;
      }
    }
  }
  if ($mode === 'toggle') {
    $coupon_id = (int)($_POST['coupon_id'] ?? 0);
    $stmt = $pdo->prepare("UPDATE coupon_codes SET is_active = IF(is_active=1,0,1) WHERE id=?");
    $stmt->execute([$coupon_id]);
    $msg = "<div class='alert alert-success'>Coupon status toggled.</div>";
  }
  if ($mode === 'delete') {
    $coupon_id = (int)($_POST['coupon_id'] ?? 0);
    $stmt = $pdo->prepare("DELETE FROM coupon_codes WHERE id=?");
    $stmt->execute([$coupon_id]);
    $msg = "<div class='alert alert-success'>Coupon deleted.</div>";
    $action = '';
    $id = 0;
  }
}

if ($action === 'edit' || $action === 'add') {
  $coupon = ['id'=>0,'code'=>'','discount_type'=>'fixed','discount_value'=>0,'min_amount'=>0,'max_uses'=>null,'used_count'=>0,'valid_from'=>null,'valid_to'=>null,'is_active'=>1];
  if ($action === 'edit') {
    $stmt = $pdo->prepare("SELECT * FROM coupon_codes WHERE id=?");
    $stmt->execute([$id]);
    $coupon = $stmt->fetch();
    if (!$coupon) { echo "<div class='alert alert-danger'>Coupon not found</div>"; require_once __DIR__.'/partials/bottom.php'; exit; }
  }
  ?>
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h4 class="fw-bold mb-0"><?php echo $action==='add'?'Create Coupon':'Edit Coupon'; ?></h4>
      <div class="text-muted small">Coupons apply at user app checkout when booking services.</div>
    </div>
    <a class="btn btn-outline-dark" href="coupons.php">Back</a>
  </div>

  <?php echo $msg; ?>

  <div class="card p-4">
    <form method="post">
      <input type="hidden" name="mode" value="save">
      <input type="hidden" name="coupon_id" value="<?php echo (int)$coupon['id']; ?>">
      <div class="row g-3">
        <div class="col-md-4">
          <label class="form-label">Coupon Code</label>
          <input class="form-control" name="code" required value="<?php echo htmlspecialchars($coupon['code']); ?>" placeholder="e.g. WELCOME50">
        </div>
        <div class="col-md-4">
          <label class="form-label">Discount Type</label>
          <select class="form-select" name="discount_type">
            <option value="fixed" <?php echo $coupon['discount_type']==='fixed'?'selected':''; ?>>Fixed (₹)</option>
            <option value="percentage" <?php echo $coupon['discount_type']==='percentage'?'selected':''; ?>>Percentage (%)</option>
          </select>
        </div>
        <div class="col-md-4">
          <label class="form-label">Discount Value</label>
          <input class="form-control" type="number" name="discount_value" min="1" max="100" required value="<?php echo (int)$coupon['discount_value']; ?>" placeholder="50 or 10">
        </div>

        <div class="col-md-4">
          <label class="form-label">Min Amount (₹)</label>
          <input class="form-control" type="number" name="min_amount" min="0" value="<?php echo (int)$coupon['min_amount']; ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Max Uses (blank = unlimited)</label>
          <input class="form-control" type="number" name="max_uses" min="0" value="<?php echo $coupon['max_uses'] !== null ? (int)$coupon['max_uses'] : ''; ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Used</label>
          <input class="form-control" type="text" value="<?php echo (int)$coupon['used_count']; ?>" readonly>
        </div>

        <div class="col-md-4">
          <label class="form-label">Valid From (optional)</label>
          <input class="form-control" type="datetime-local" name="valid_from" value="<?php echo $coupon['valid_from'] ? date('Y-m-d\TH:i', strtotime($coupon['valid_from'])) : ''; ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Valid To (optional)</label>
          <input class="form-control" type="datetime-local" name="valid_to" value="<?php echo $coupon['valid_to'] ? date('Y-m-d\TH:i', strtotime($coupon['valid_to'])) : ''; ?>">
        </div>

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

        <div class="col-12">
          <button class="btn btn-dark" type="submit">Save Coupon</button>
        </div>
      </div>
    </form>
  </div>
  <?php
  require_once __DIR__ . '/partials/bottom.php';
  exit;
}

$coupons = $pdo->query("SELECT * FROM coupon_codes ORDER BY created_at DESC")->fetchAll();
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="fw-bold mb-0">Coupon Codes</h4>
    <div class="text-muted small">Manage coupons for user app checkout (apply at payment).</div>
  </div>
  <a class="btn btn-dark" href="coupons.php?action=add">+ Create Coupon</a>
</div>

<?php echo $msg; ?>

<div class="card p-3">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead>
        <tr>
          <th>Code</th>
          <th>Type</th>
          <th>Value</th>
          <th>Min Amt</th>
          <th>Used / Max</th>
          <th>Validity</th>
          <th>Status</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($coupons as $c): ?>
        <tr>
          <td class="fw-semibold"><code><?php echo htmlspecialchars($c['code']); ?></code></td>
          <td><?php echo $c['discount_type']==='percentage'?'%':'₹'; ?></td>
          <td><?php echo $c['discount_type']==='percentage' ? $c['discount_value'].'%' : '₹'.$c['discount_value']; ?></td>
          <td>₹<?php echo (int)$c['min_amount']; ?></td>
          <td><?php echo (int)$c['used_count']; ?> / <?php echo $c['max_uses']===null?'∞':$c['max_uses']; ?></td>
          <td class="small">
            <?php echo $c['valid_from'] ? date('M d', strtotime($c['valid_from'])) : '—'; ?>
            to <?php echo $c['valid_to'] ? date('M d, Y', strtotime($c['valid_to'])) : 'No expiry'; ?>
          </td>
          <td>
            <?php if ((int)$c['is_active']===1): ?>
              <span class="badge text-bg-success">active</span>
            <?php else: ?>
              <span class="badge text-bg-secondary">disabled</span>
            <?php endif; ?>
          </td>
          <td class="text-end">
            <a class="btn btn-sm btn-outline-dark" href="coupons.php?action=edit&id=<?php echo (int)$c['id']; ?>">Edit</a>
            <form method="post" style="display:inline;">
              <input type="hidden" name="mode" value="toggle">
              <input type="hidden" name="coupon_id" value="<?php echo (int)$c['id']; ?>">
              <button class="btn btn-sm btn-dark" type="submit"><?php echo (int)$c['is_active']===1?'Disable':'Enable'; ?></button>
            </form>
            <form method="post" style="display:inline;" onsubmit="return confirm('Delete this coupon?');">
              <input type="hidden" name="mode" value="delete">
              <input type="hidden" name="coupon_id" value="<?php echo (int)$c['id']; ?>">
              <button class="btn btn-sm btn-outline-danger" type="submit">Delete</button>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (count($coupons)===0): ?>
        <tr><td colspan="8" class="text-muted">No coupons. Run database/coupon_codes.sql first.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
