<?php
session_start();

if (!isset($_SESSION['username']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: login.html?error=unauthorized");
    exit();
}

require 'db_connect.php';

date_default_timezone_set('Africa/Nairobi');

$page_title = "Purchases | Admin";
$username   = $_SESSION['username'];
$message    = "";

/* Messages from redirects */
if (isset($_GET['added'])) {
    $message = "<div class='alert alert-success'>✔ Purchase added successfully.</div>";
} elseif (isset($_GET['updated'])) {
    $message = "<div class='alert alert-success'>✔ Purchase updated successfully.</div>";
} elseif (isset($_GET['deleted'])) {
    $message = "<div class='alert alert-success'>✔ Purchase deleted successfully.</div>";
}

/* -------------------------------
   PAGINATION + SHOW X ENTRIES
--------------------------------- */
$limit_options = [10, 15, 25, 50, 100];
$raw_limit     = $_GET['limit'] ?? 15;
$page          = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

$is_all = ($raw_limit === 'all');

if ($is_all) {
    $limit  = null;
} else {
    $limit = (int)$raw_limit;
    if (!in_array($limit, $limit_options, true)) {
        $limit = 15;
    }
}

/* -------------------------------
   DATE FILTERS
--------------------------------- */
$start_date = trim($_GET['start_date'] ?? '');
$end_date   = trim($_GET['end_date'] ?? '');

// Simple validation (YYYY-MM-DD)
if ($start_date !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date)) {
    $start_date = '';
}
if ($end_date !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_date)) {
    $end_date = '';
}

/* -------------------------------
   SEARCH PURCHASES
--------------------------------- */
$search = trim($_GET['search'] ?? '');

/* -------------------------------
   BUILD FILTERS (NO ALIAS HERE)
--------------------------------- */
$filterSql      = '';
$filterTypes    = '';
$filterParams   = [];
$filterClauses  = [];

if ($start_date !== '' && $end_date !== '') {
    $filterClauses[] = "DATE(purchase_date) BETWEEN ? AND ?";
    $filterTypes    .= "ss";
    $filterParams[]  = $start_date;
    $filterParams[]  = $end_date;
} elseif ($start_date !== '') {
    $filterClauses[] = "DATE(purchase_date) >= ?";
    $filterTypes    .= "s";
    $filterParams[]  = $start_date;
} elseif ($end_date !== '') {
    $filterClauses[] = "DATE(purchase_date) <= ?";
    $filterTypes    .= "s";
    $filterParams[]  = $end_date;
}

if ($search !== '') {
    $filterClauses[] = "(product_name LIKE ? OR supplier_name LIKE ?)";
    $filterTypes    .= "ss";
    $filterParams[]  = "%$search%";
    $filterParams[]  = "%$search%";
}

if (!empty($filterClauses)) {
    $filterSql = " WHERE " . implode(" AND ", $filterClauses);
}

$filter_active = ($start_date !== '' || $end_date !== '' || $search !== '');

/* -------------------------------
   ADD / UPDATE PURCHASE (ADMIN)
   (supplier name is typed)
--------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $purchase_id   = (int)($_POST['purchase_id'] ?? 0);  // >0 means edit
    $supplier_name = trim($_POST['supplier_name'] ?? '');
    $product_name  = trim($_POST['product_name'] ?? '');
    $quantity      = (int)($_POST['quantity'] ?? 0);
    $unit_price    = (float)($_POST['unit_price'] ?? 0);
    $purchase_date = date('Y-m-d'); // today's date for new records

    if ($supplier_name === '' || $product_name === '' || $quantity <= 0 || $unit_price <= 0) {
        $message = "<div class='alert alert-error'>Please provide valid purchase details.</div>";
    } else {
        $total_price = $quantity * $unit_price;

        if ($purchase_id > 0) {
            // UPDATE existing purchase
            $stmt = $conn->prepare("
                UPDATE purchases
                SET supplier_name = ?, product_name = ?, quantity = ?, unit_price = ?, total_price = ?
                WHERE id = ?
            ");

            if ($stmt) {
                $stmt->bind_param(
                    "ssiddi",
                    $supplier_name,
                    $product_name,
                    $quantity,
                    $unit_price,
                    $total_price,
                    $purchase_id
                );

                if ($stmt->execute()) {
                    header("Location: admin_purchases.php?updated=1");
                    exit();
                } else {
                    $message = "<div class='alert alert-error'>❌ Error updating purchase: " . htmlspecialchars($stmt->error) . "</div>";
                }
                $stmt->close();
            } else {
                $message = "<div class='alert alert-error'>❌ Error preparing update: " . htmlspecialchars($conn->error) . "</div>";
            }

        } else {
            // INSERT new purchase
            $stmt = $conn->prepare("
                INSERT INTO purchases (supplier_name, product_name, quantity, unit_price, total_price, purchase_date)
                VALUES (?, ?, ?, ?, ?, ?)
            ");

            if ($stmt) {
                $stmt->bind_param(
                    "ssidds",
                    $supplier_name,
                    $product_name,
                    $quantity,
                    $unit_price,
                    $total_price,
                    $purchase_date
                );

                if ($stmt->execute()) {
                    header("Location: admin_purchases.php?added=1");
                    exit();
                } else {
                    $message = "<div class='alert alert-error'>❌ Error adding purchase: " . htmlspecialchars($stmt->error) . "</div>";
                }
                $stmt->close();
            } else {
                $message = "<div class='alert alert-error'>❌ Error preparing insert: " . htmlspecialchars($conn->error) . "</div>";
            }
        }
    }
}

/* -------------------------------
   DELETE PURCHASE
--------------------------------- */
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    if ($id > 0) {
        $sql = "DELETE FROM purchases WHERE id = $id";
        if ($conn->query($sql)) {
            header("Location: admin_purchases.php?deleted=1");
            exit();
        } else {
            $message = "<div class='alert alert-error'>❌ Delete failed: " . htmlspecialchars($conn->error) . "</div>";
        }
    }
}

/* -------------------------------
   FETCH PURCHASE TO EDIT (IF ANY)
--------------------------------- */
$editing       = false;
$edit_purchase = null;

if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    if ($edit_id > 0) {
        $stmt = $conn->prepare("SELECT * FROM purchases WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param("i", $edit_id);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($res && $res->num_rows > 0) {
                $edit_purchase = $res->fetch_assoc();
                $editing = true;
            } else {
                $message = "<div class='alert alert-error'>Purchase not found.</div>";
            }
            $stmt->close();
        }
    }
}

/* -------------------------------
   COUNT TOTAL ROWS (WITH FILTER)
--------------------------------- */
$countSql = "SELECT COUNT(*) AS total FROM purchases" . $filterSql;
$countStmt = $conn->prepare($countSql);

if ($countStmt === false) {
    die("Error preparing count query: " . htmlspecialchars($conn->error));
}

if ($filterSql !== '') {
    $countStmt->bind_param($filterTypes, ...$filterParams);
}

$countStmt->execute();
$countResult = $countStmt->get_result();
$totalRows   = (int)($countResult->fetch_assoc()['total'] ?? 0);
$countStmt->close();

/* -------------------------------
   GRAND TOTAL (WITH FILTER)
--------------------------------- */
$grandSql = "SELECT SUM(total_price) AS grand_total FROM purchases" . $filterSql;
$grandStmt = $conn->prepare($grandSql);

if ($grandStmt === false) {
    die("Error preparing sum query: " . htmlspecialchars($conn->error));
}

if ($filterSql !== '') {
    $grandStmt->bind_param($filterTypes, ...$filterParams);
}

$grandStmt->execute();
$grandResult = $grandStmt->get_result();
$grand_total = (float)($grandResult->fetch_assoc()['grand_total'] ?? 0);
$grandStmt->close();

$grand_label = $filter_active ? "Grand total (filtered range)" : "Grand total (all purchases)";

/* -------------------------------
   FINALIZE PAGINATION
--------------------------------- */
if ($is_all) {
    $totalPages = 1;
    $page       = 1;
    $offset     = 0;
} else {
    $totalPages = max(1, (int)ceil($totalRows / $limit));
    if ($page > $totalPages) {
        $page = $totalPages;
    }
    $offset = ($page - 1) * $limit;
}

/* -------------------------------
   FETCH PAGINATED PURCHASES (WITH FILTER)
--------------------------------- */
$listSql = "SELECT p.id, p.purchase_date, p.product_name, p.quantity, p.unit_price, p.total_price, p.supplier_name
            FROM purchases p" . $filterSql . " ORDER BY purchase_date DESC";

if (!$is_all) {
    $listSql .= " LIMIT ? OFFSET ?";
}

$listStmt = $conn->prepare($listSql);

if ($listStmt === false) {
    die("Error preparing list query: " . htmlspecialchars($conn->error));
}

if ($is_all) {
    if ($filterSql !== '') {
        $listStmt->bind_param($filterTypes, ...$filterParams);
    }
} else {
    if ($filterSql !== '') {
        $types  = $filterTypes . "ii";
        $params = array_merge($filterParams, [$limit, $offset]);
        $listStmt->bind_param($types, ...$params);
    } else {
        $listStmt->bind_param("ii", $limit, $offset);
    }
}

$listStmt->execute();
$purchases = $listStmt->get_result();

/* -------------------------------
   FINALIZE PAGINATION
--------------------------------- */
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include 'head.php'; ?>
    <link rel="stylesheet" href="admin_purchases.css">
</head>
<body>

<?php include 'sidebar.php'; ?>

<div class="content-wrapper" id="content-wrapper">
    <div class="topbar">
        <div class="topbar-left">
            <span class="menu-btn" onclick="toggleAdminSidebar()">☰</span>
            <span class="topbar-title">Admin Panel</span>
        </div>
        <div class="topbar-right">
            <button class="theme-toggle" type="button" onclick="toggleAdminTheme()">
                🌓 Theme
            </button>
            <span class="topbar-user">
                Logged in as <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></strong>
            </span>
        </div>
    </div>

    <div class="content-inner">
        <div class="page-header">
            <div>
                <div class="page-title">Manage Purchases</div>
                <div class="page-subtitle">
                    Add and review recorded purchases.
                    <?php if ($filter_active): ?>
                        (Filtered view)
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Add / Edit Purchase Form -->
        <div class="page-card">
            <div class="page-card-title">
                <?= $editing ? 'Edit Purchase' : 'Add Purchase' ?>
            </div>

            <?php if ($message): ?>
                <?= $message ?>
            <?php endif; ?>

            <form method="POST" class="expense-form">
                <?php if ($editing && $edit_purchase): ?>
                    <input type="hidden" name="purchase_id" value="<?= (int)$edit_purchase['id'] ?>">
                <?php endif; ?>

                <label for="supplier_name">Supplier Name</label>
                <input
                    type="text"
                    id="supplier_name"
                    name="supplier_name"
                    required
                    placeholder="Type the supplier's name"
                    value="<?= htmlspecialchars($editing && $edit_purchase ? $edit_purchase['supplier_name'] : '') ?>"
                >

                <label for="product_name">Product Name</label>
                <input
                    type="text"
                    id="product_name"
                    name="product_name"
                    required
                    placeholder="Enter product name"
                    value="<?= htmlspecialchars($editing && $edit_purchase ? $edit_purchase['product_name'] : '') ?>"
                >

                <label for="quantity">Quantity</label>
                <input
                    type="number"
                    id="quantity"
                    name="quantity"
                    required
                    placeholder="Enter quantity"
                    value="<?= htmlspecialchars($editing && $edit_purchase ? $edit_purchase['quantity'] : '') ?>"
                >

                <label for="unit_price">Unit Price (KES)</label>
                <input
                    type="number"
                    step="0.01"
                    id="unit_price"
                    name="unit_price"
                    required
                    placeholder="Enter unit price"
                    value="<?= htmlspecialchars($editing && $edit_purchase ? $edit_purchase['unit_price'] : '') ?>"
                >

                <button type="submit" class="btn-primary">
                    <?= $editing ? 'Update Purchase' : 'Add Purchase' ?>
                </button>
            </form>
        </div>

        <!-- Purchases Table + Filters -->
        <div class="page-card">

            <div class="pos-table-header">
                <div>
                    <h3>Purchases history</h3>
                    <p>
                        <?php if ($totalRows > 0): ?>
                            Showing page <?= $page ?> of <?= $is_all ? 1 : $totalPages ?><?= $filter_active ? ' (filtered)' : '' ?>.
                        <?php else: ?>
                            No purchases found.
                        <?php endif; ?>
                        <?php if ($filter_active): ?>
                            <br>
                            Filter:
                            <?php if ($start_date !== ''): ?>
                                from <?= htmlspecialchars($start_date) ?>
                            <?php endif; ?>
                            <?php if ($end_date !== ''): ?>
                                to <?= htmlspecialchars($end_date) ?>
                            <?php endif; ?>
                            <?php if ($search !== ''): ?>
                                | search: "<?= htmlspecialchars($search) ?>"
                            <?php endif; ?>
                        <?php endif; ?>
                    </p>
                </div>

                <div class="pos-controls">
                    <span class="badge-muted">
                        <?= htmlspecialchars($grand_label) ?>:
                        KES <?= number_format($grand_total, 2) ?>
                    </span>

                    <!-- Date + Search Filters -->
                    <form method="GET" class="date-filter-form">
                        <span>From</span>
                        <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>">
                        <span>to</span>
                        <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>">
                        <input type="text" name="search" placeholder="Search supplier / product"
                               value="<?= htmlspecialchars($search) ?>" style="min-width:180px;">
                        <input type="hidden" name="limit" value="<?= $is_all ? 'all' : $limit ?>">
                        <button type="submit">Apply</button>
                        <?php if ($filter_active): ?>
                            <a href="admin_purchases.php" class="clear-btn">Clear</a>
                        <?php endif; ?>
                    </form>

                    <!-- Show X entries -->
                    <form method="GET" class="entries-form">
                        <label>Show</label>
                        <select name="limit" onchange="this.form.submit()">
                            <?php foreach($limit_options as $opt): ?>
                                <option value="<?= $opt ?>"
                                    <?= (!$is_all && (int)$limit === (int)$opt) ? 'selected' : '' ?>>
                                    <?= $opt ?>
                                </option>
                            <?php endforeach; ?>
                            <option value="all" <?= $is_all ? 'selected' : '' ?>>All</option>
                        </select>
                        <input type="hidden" name="start_date" value="<?= htmlspecialchars($start_date) ?>">
                        <input type="hidden" name="end_date"   value="<?= htmlspecialchars($end_date) ?>">
                        <input type="hidden" name="search"     value="<?= htmlspecialchars($search) ?>">
                        <span style="color:var(--text-muted);">entries</span>
                    </form>
                </div>
            </div>

            <div class="table-wrapper">
                <table class="pos-table">
                    <thead>
                    <tr>
                        <th>Supplier</th>
                        <th>Product Name</th>
                        <th>Quantity</th>
                        <th>Unit Price</th>
                        <th>Total Price</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if ($purchases && $purchases->num_rows > 0): ?>
                        <?php while ($purchase = $purchases->fetch_assoc()): ?>
                            <tr>
                                <td><?= htmlspecialchars($purchase['supplier_name']) ?></td>
                                <td><?= htmlspecialchars($purchase['product_name']) ?></td>
                                <td><?= (int)$purchase['quantity'] ?></td>
                                <td><?= number_format($purchase['unit_price'], 2) ?></td>
                                <td><?= number_format($purchase['total_price'], 2) ?></td>
                                <td><?= htmlspecialchars($purchase['purchase_date']) ?></td>
                                <td>
                                    <a class="edit-btn" href="admin_purchases.php?edit=<?= (int)$purchase['id'] ?>">
                                        Edit
                                    </a>
                                    <a class="delete-btn"
                                       href="admin_purchases.php?delete=<?= (int)$purchase['id'] ?>"
                                       onclick="return confirm('Are you sure you want to delete this purchase?');">
                                        Delete
                                    </a>
                                     <!-- Button to go to serial number assignment page -->
    <a class="btn-primary" href="add_serial_numbers.php?purchase_id=<?= $purchase['id'] ?>">Assign Serial Numbers</a>
    <a class="btn-primary" href="view_serial_numbers.php?purchase_id=<?= $purchase['id'] ?>">View Serial Numbers</a>
</td>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="empty-row">No purchases found.</td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if (!$is_all && $totalPages > 1): ?>
                <div class="pagination">
                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                        <a class="page-btn <?= ($i == $page) ? 'active' : '' ?>"
                           href="?page=<?= $i ?>
                                &limit=<?= urlencode($is_all ? 'all' : (string)$limit) ?>
                                &start_date=<?= urlencode($start_date) ?>
                                &end_date=<?= urlencode($end_date) ?>
                                &search=<?= urlencode($search) ?>">
                            <?= $i ?>
                        </a>
                    <?php endfor; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function toggleAdminSidebar() {
    const sidebar = document.getElementById('sidebar');
    const wrapper = document.getElementById('content-wrapper');
    if (!sidebar || !wrapper) return;

    const isHidden = sidebar.classList.toggle('hidden');
    if (isHidden) {
        wrapper.classList.add('fullwidth');
    } else {
        wrapper.classList.remove('fullwidth');
    }
}
</script>

</body>
</html>
 