<?php
// public/suppliers.php
require_once __DIR__ . '/../helpers/auth.php';
require_once __DIR__ . '/../helpers/audit.php';

require_role(['admin','staff']);

$pdo = db();
$title = "Suppliers - IMS";

// ---------------------------
// Helpers
// ---------------------------
function get_str(string $k): string { return trim((string)($_GET[$k] ?? '')); }
function post_str(string $k): string { return trim((string)($_POST[$k] ?? '')); }
function post_int(string $k): int { return (int)($_POST[$k] ?? 0); }

// ---------------------------
// Filters
// ---------------------------
$q = get_str('q');

// ---------------------------
// Actions
// ---------------------------
$action = $_POST['action'] ?? '';
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ADD
    if ($action === 'add') {
        $supplier_code  = post_str('supplier_code'); // optional
        $name           = post_str('name');          // required
        $city           = post_str('city');
        $country        = post_str('country');
        $contact_person = post_str('contact_person');
        $phone          = post_str('phone');
        $email          = post_str('email');
        $address        = post_str('address');

        if ($name === '') {
            $error = "Supplier Name is required.";
        } else {
            try {
                $stmt = $pdo->prepare("
                    INSERT INTO suppliers
                        (supplier_code, name, city, country, contact_person, phone, email, address, is_active, created_at)
                    VALUES
                        (:supplier_code, :name, :city, :country, :contact_person, :phone, :email, :address, 1, NOW())
                ");
                $stmt->execute([
                    'supplier_code'  => ($supplier_code !== '' ? $supplier_code : null),
                    'name'           => $name,
                    'city'           => ($city !== '' ? $city : null),
                    'country'        => ($country !== '' ? $country : null),
                    'contact_person' => ($contact_person !== '' ? $contact_person : null),
                    'phone'          => ($phone !== '' ? $phone : null),
                    'email'          => ($email !== '' ? $email : null),
                    'address'        => ($address !== '' ? $address : null),
                ]);

                $success = "Supplier added successfully.";

                audit_log(
                    'CREATE_SUPPLIER',
                    'suppliers',
                    (string)$pdo->lastInsertId(),
                    $name
                );

            } catch (PDOException $e) {
                $error = "Error adding supplier: " . $e->getMessage();
            }
        }
    }

    // EDIT
    if ($action === 'edit') {
        $id             = post_int('id');
        $supplier_code  = post_str('supplier_code');
        $name           = post_str('name');
        $city           = post_str('city');
        $country        = post_str('country');
        $contact_person = post_str('contact_person');
        $phone          = post_str('phone');
        $email          = post_str('email');
        $address        = post_str('address');
        $is_active      = isset($_POST['is_active']) ? 1 : 0;

        if ($id <= 0 || $name === '') {
            $error = "Invalid supplier data. Name is required.";
        } else {
            try {
                $stmt = $pdo->prepare("
                    UPDATE suppliers
                    SET supplier_code = :supplier_code,
                        name = :name,
                        city = :city,
                        country = :country,
                        contact_person = :contact_person,
                        phone = :phone,
                        email = :email,
                        address = :address,
                        is_active = :is_active
                    WHERE id = :id
                    LIMIT 1
                ");
                $stmt->execute([
                    'supplier_code'  => ($supplier_code !== '' ? $supplier_code : null),
                    'name'           => $name,
                    'city'           => ($city !== '' ? $city : null),
                    'country'        => ($country !== '' ? $country : null),
                    'contact_person' => ($contact_person !== '' ? $contact_person : null),
                    'phone'          => ($phone !== '' ? $phone : null),
                    'email'          => ($email !== '' ? $email : null),
                    'address'        => ($address !== '' ? $address : null),
                    'is_active'      => $is_active,
                    'id'             => $id,
                ]);

                $success = "Supplier updated successfully.";

                audit_log(
                    'UPDATE_SUPPLIER',
                    'suppliers',
                    (string)$id,
                    $name
                );

            } catch (PDOException $e) {
                $error = "Error updating supplier: " . $e->getMessage();
            }
        }
    }

    // DELETE (soft delete)
    if ($action === 'delete') {
        $id = post_int('id');
        if ($id <= 0) {
            $error = "Invalid supplier ID.";
        } else {
            try {
                $stmt = $pdo->prepare("UPDATE suppliers SET is_active = 0 WHERE id = :id LIMIT 1");
                $stmt->execute(['id' => $id]);

                $success = "Supplier set to Inactive.";

                audit_log(
                    'DELETE_SUPPLIER',
                    'suppliers',
                    (string)$id,
                    null
                );

            } catch (PDOException $e) {
                $error = "Error deleting supplier: " . $e->getMessage();
            }
        }
    }
}

// ---------------------------
// Edit mode (GET)
// ---------------------------
$edit_id = (int)($_GET['edit'] ?? 0);
$edit_supplier = null;

if ($edit_id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM suppliers WHERE id = :id LIMIT 1");
    $stmt->execute(['id' => $edit_id]);
    $edit_supplier = $stmt->fetch();

    if (!$edit_supplier) {
        $error = "Supplier not found.";
        $edit_id = 0;
    }
}

// ---------------------------
// List suppliers (WITH SEARCH FIX)
// ---------------------------
$sql = "
  SELECT id, supplier_code, name, city, country, is_active, created_at
  FROM suppliers
  WHERE 1=1
";

$params = [];

if ($q !== '') {
    $sql .= " AND (
        supplier_code LIKE :q1
        OR name LIKE :q2
        OR city LIKE :q3
        OR country LIKE :q4
    ) ";

    $like = '%' . $q . '%';
    $params['q1'] = $like;
    $params['q2'] = $like;
    $params['q3'] = $like;
    $params['q4'] = $like;
}


$sql .= " ORDER BY created_at DESC, id DESC ";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$suppliers = $stmt->fetchAll();

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between mb-3">
    <h4 class="mb-0">Suppliers</h4>

    <form class="d-flex gap-2" method="GET">
      <input class="form-control form-control-sm" name="q" placeholder="Search code/name/city/country..." value="<?= htmlspecialchars($q) ?>">
      <button class="btn btn-sm btn-outline-primary" type="submit">Search</button>
      <a class="btn btn-sm btn-outline-secondary" href="suppliers.php">Reset</a>
    </form>
  </div>

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

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

  <div class="row g-3">
    <!-- Form -->
    <div class="col-12 col-lg-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <h5 class="card-title mb-3"><?= $edit_id > 0 ? 'Edit Supplier' : 'Add Supplier' ?></h5>

          <form method="POST">
            <input type="hidden" name="action" value="<?= $edit_id > 0 ? 'edit' : 'add' ?>">
            <?php if ($edit_id > 0): ?>
              <input type="hidden" name="id" value="<?= (int)$edit_supplier['id'] ?>">
            <?php endif; ?>

            <div class="mb-2">
              <label class="form-label">Code</label>
              <input class="form-control" name="supplier_code" value="<?= htmlspecialchars($edit_supplier['supplier_code'] ?? '') ?>">
              <div class="form-text">Optional (e.g. 50001).</div>
            </div>

            <div class="mb-2">
              <label class="form-label">Name *</label>
              <input class="form-control" name="name" required value="<?= htmlspecialchars($edit_supplier['name'] ?? '') ?>">
            </div>

            <div class="mb-2">
              <label class="form-label">City</label>
              <input class="form-control" name="city" value="<?= htmlspecialchars($edit_supplier['city'] ?? '') ?>">
            </div>

            <div class="mb-2">
              <label class="form-label">Country</label>
              <input class="form-control" name="country" value="<?= htmlspecialchars($edit_supplier['country'] ?? '') ?>">
            </div>

            <details class="mb-2">
              <summary class="small text-muted">More details (optional)</summary>

              <div class="mt-2">
                <label class="form-label">Contact Person</label>
                <input class="form-control" name="contact_person" value="<?= htmlspecialchars($edit_supplier['contact_person'] ?? '') ?>">
              </div>

              <div class="mt-2">
                <label class="form-label">Phone</label>
                <input class="form-control" name="phone" value="<?= htmlspecialchars($edit_supplier['phone'] ?? '') ?>">
              </div>

              <div class="mt-2">
                <label class="form-label">Email</label>
                <input class="form-control" name="email" type="email" value="<?= htmlspecialchars($edit_supplier['email'] ?? '') ?>">
              </div>

              <div class="mt-2">
                <label class="form-label">Address</label>
                <textarea class="form-control" name="address" rows="2"><?= htmlspecialchars($edit_supplier['address'] ?? '') ?></textarea>
              </div>
            </details>

            <?php if ($edit_id > 0): ?>
              <div class="form-check mb-3">
                <?php $checked = ((int)($edit_supplier['is_active'] ?? 1) === 1) ? 'checked' : ''; ?>
                <input class="form-check-input" type="checkbox" name="is_active" id="is_active" <?= $checked ?>>
                <label class="form-check-label" for="is_active">Active</label>
              </div>
            <?php endif; ?>

            <button class="btn btn-primary w-100" type="submit">
              <?= $edit_id > 0 ? 'Save Changes' : 'Add Supplier' ?>
            </button>

            <?php if ($edit_id > 0): ?>
              <a class="btn btn-outline-secondary w-100 mt-2" href="suppliers.php">Cancel</a>
            <?php endif; ?>
          </form>
        </div>
      </div>
    </div>

    <!-- Table -->
    <div class="col-12 col-lg-8">
      <div class="card shadow-sm">
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead>
                <tr>
                  <th>Code</th>
                  <th>Name</th>
                  <th>City</th>
                  <th>Country</th>
                  <th class="text-center">Active</th>
                  <th style="width:220px;"></th>
                </tr>
              </thead>
              <tbody>
                <?php if (!$suppliers): ?>
                  <tr><td colspan="6" class="text-muted">No suppliers found.</td></tr>
                <?php else: ?>
                  <?php foreach ($suppliers as $s): ?>
                    <tr>
                      <td><?= htmlspecialchars($s['supplier_code'] ?? '-') ?></td>
                      <td><?= htmlspecialchars($s['name']) ?></td>
                      <td><?= htmlspecialchars($s['city'] ?? '-') ?></td>
                      <td><?= htmlspecialchars($s['country'] ?? '-') ?></td>
                      <td class="text-center"><?= ((int)$s['is_active'] === 1) ? '✅' : '❌' ?></td>
                      <td class="text-end">
                        <a class="btn btn-outline-dark btn-sm" href="supplier_view.php?id=<?= (int)$s['id'] ?>">View</a>
                        <a class="btn btn-outline-primary btn-sm" href="suppliers.php?edit=<?= (int)$s['id'] ?>">Edit</a>

                        <form method="POST" class="d-inline" onsubmit="return confirm('Set this supplier to Inactive?');">
                          <input type="hidden" name="action" value="delete">
                          <input type="hidden" name="id" value="<?= (int)$s['id'] ?>">
                          <button class="btn btn-outline-danger btn-sm" type="submit">Deactivate</button>
                        </form>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <div class="text-muted small">
            Note: “Deactivate” sets supplier to inactive (safer than deleting).
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
