<?php
declare(strict_types=1);
/**
 * modules/quotes/delete.php
 *
 * Soft-delete (disable) a quote safely.
 * - Tries to set status = 'deleted' if ENUM allows, else falls back to 'rejected'
 * - Appends a note with timestamp & user
 * - (Optional) remove generated PDF file if exists
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Fetch quote
 *  3) POST handler (perform soft delete)
 *  4) Confirmation view (GET)
 */

////////////////////////////////////////////////////////////////
// 1) Bootstrap & guards
////////////////////////////////////////////////////////////////
require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Admin','Ops','sales']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
if ($id <= 0) redirect(url_modules('quotes/list.php'));

$errors = [];
$notice = null;

////////////////////////////////////////////////////////////////
// 2) Fetch quote
////////////////////////////////////////////////////////////////
$sel = db()->prepare("
  SELECT q.*, p.name AS partner_name, c.name AS corporate_name
    FROM quotes q
    LEFT JOIN partners  p ON p.id = q.partner_id
    LEFT JOIN corporates c ON c.id = q.corporate_id
   WHERE q.id = :id AND q.company_id = :cid
   LIMIT 1
");
$sel->execute([':id' => $id, ':cid' => $cid]);
$quote = $sel->fetch();
if (!$quote) redirect(url_modules('quotes/list.php'));

/** Helper: does quotes.status ENUM contain 'deleted'? */
function quotes_status_allows_deleted(): bool {
  try {
    $q = db()->prepare("
      SELECT COLUMN_TYPE
        FROM INFORMATION_SCHEMA.COLUMNS
       WHERE TABLE_SCHEMA = DATABASE()
         AND TABLE_NAME   = 'quotes'
         AND COLUMN_NAME  = 'status'
       LIMIT 1
    ");
    $q->execute();
    $colType = (string)$q->fetchColumn();
    // COLUMN_TYPE like: enum('draft','sent','accepted','rejected')
    return stripos($colType, "'deleted'") !== false;
  } catch (Throwable $e) {
    return false;
  }
}

/** Helper: compute subtotal (for confirmation summary) */
function quote_subtotal(int $quoteId): float {
  try {
    $stmt = db()->prepare("SELECT COALESCE(SUM(COALESCE(line_total, quantity*unit_price)),0) AS s FROM quote_lines WHERE quote_id=:qid");
    $stmt->execute([':qid'=>$quoteId]);
    $row = $stmt->fetch();
    return (float)($row['s'] ?? 0);
  } catch (Throwable $e) {
    return 0.0;
  }
}

////////////////////////////////////////////////////////////////
// 3) POST handler (perform soft delete)
////////////////////////////////////////////////////////////////
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    // Determine target status safely
    $targetStatus = quotes_status_allows_deleted() ? 'deleted' : 'rejected';

    // Append a small audit note into notes column
    $appendNote = "\n[Deleted " . date('Y-m-d H:i') . " by " . e((string)($user['name'] ?? 'user#'.($user['id'] ?? '?'))) . "]";
    $newNotes   = (string)($quote['notes'] ?? '');
    $newNotes  .= $appendNote;

    // Optional: remove PDF if present (does not error if missing)
    if (!empty($quote['pdf_url'])) {
      $abs = project_root() . '/public/' . ltrim((string)$quote['pdf_url'], '/');
      if (is_file($abs)) @unlink($abs);
    }

    $upd = db()->prepare("
      UPDATE quotes
         SET status = :st,
             notes  = :notes,
             updated_at = NOW()
       WHERE id = :id AND company_id = :cid
       LIMIT 1
    ");
    $upd->execute([
      ':st'    => $targetStatus,
      ':notes' => $newNotes,
      ':id'    => $id,
      ':cid'   => $cid,
    ]);

    audit_log('quote.delete', 'quote', $id, ['new_status'=>$targetStatus]);

    redirect(url_modules('quotes/list.php') . '?deleted=1');
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unable to delete the quote.';
  }
}

////////////////////////////////////////////////////////////////
// 4) Confirmation view (GET)
////////////////////////////////////////////////////////////////
include dirname(__DIR__, 2) . '/includes/header.php';

$subtotal = quote_subtotal($id);
$discount = (float)($quote['discount'] ?? 0.0);
$grand    = max(0, $subtotal - $discount);
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Delete Quote #<?= (int)$quote['id'] ?></h1>
  <a class="btn btn-outline-secondary" href="<?= e(url_modules('quotes/list.php')) ?>">Back</a>
</div>

<?php if ($errors): ?>
  <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e) echo '<li>'.e($e).'</li>'; ?></ul></div>
<?php endif; ?>

<div class="card shadow-sm">
  <div class="card-body">
    <h2 class="h6 text-uppercase text-muted mb-3">Are you sure you want to delete this quote?</h2>

    <div class="row g-3">
      <div class="col-md-6">
        <div class="small text-muted">Client</div>
        <div class="fw-semibold"><?= e($quote['client_name'] ?? '—') ?><?= !empty($quote['client_email']) ? ' — '.e($quote['client_email']) : '' ?></div>
      </div>
      <div class="col-md-3">
        <div class="small text-muted">Quote Date</div>
        <div class="fw-semibold"><?= e($quote['quote_date'] ?? '—') ?></div>
      </div>
      <div class="col-md-3">
        <div class="small text-muted">Status</div>
        <div class="fw-semibold"><?= e(ucfirst((string)($quote['status'] ?? 'draft'))) ?></div>
      </div>
      <div class="col-md-6">
        <div class="small text-muted">Partner / Corporate</div>
        <div class="fw-semibold">
          <?= e($quote['partner_name'] ?? '—') ?>
          <?php if (!empty($quote['corporate_name'])): ?>
            <span class="text-muted"> • </span><?= e($quote['corporate_name']) ?>
          <?php endif; ?>
        </div>
      </div>
      <div class="col-md-6">
        <div class="small text-muted">Totals</div>
        <div class="fw-semibold">
          Subtotal £<?= number_format($subtotal,2) ?> —
          Discount £<?= number_format($discount,2) ?> —
          Grand £<?= number_format($grand,2) ?>
        </div>
      </div>
    </div>

    <div class="alert alert-warning mt-3 mb-0">
      This is a <strong>soft delete</strong>: the quote will be marked as <?= quotes_status_allows_deleted() ? '<code>deleted</code>' : '<code>rejected</code>' ?> and hidden from active workflows.
    </div>

    <form method="post" class="mt-3">
      <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="id"   value="<?= (int)$id ?>">
      <button class="btn btn-danger">Yes, delete this quote</button>
      <a class="btn btn-outline-secondary ms-2" href="<?= e(url_modules('quotes/list.php')) ?>">Cancel</a>
    </form>
  </div>
</div>

<?php include dirname(__DIR__, 2) . '/includes/footer.php';
