<?php
include 'db.php';
include 'auth_check.php';

// Handle filters
$filter_item = isset($_GET['item_name']) ? $_GET['item_name'] : '';
$filter_given_to = isset($_GET['given_to']) ? $_GET['given_to'] : '';
$filter_date = isset($_GET['fault_date']) ? $_GET['fault_date'] : '';

// Pagination variables
$limit = 10; // Records per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if($page < 1) $page = 1;
$start = ($page - 1) * $limit;

// Base SQL query with JOIN to purchase_stock
$sql = "
    SELECT 
        f.id,
        f.fault_date,
        f.given_to,
        f.qty,
        f.remarks,
        COALESCE(p.item_name, f.item_name) AS item_name,
        COALESCE(p.particular_name, f.particular_name, '0') AS particular_name,
        COALESCE(p.specification, f.specification, '0') AS specification,
        COALESCE(p.model_number, f.model_number, '0') AS model_number,
        p.invoice_number
    FROM fault_stock f
    LEFT JOIN purchase_stock p 
        ON f.purchase_stock_id = p.id
";

// Apply filters
$where = [];
if ($filter_item != '') {
    $where[] = "f.item_name LIKE '%" . $conn->real_escape_string($filter_item) . "%'";
}
if ($filter_given_to != '') {
    $where[] = "f.given_to LIKE '%" . $conn->real_escape_string($filter_given_to) . "%'";
}
if ($filter_date != '') {
    $where[] = "f.fault_date = '" . $conn->real_escape_string($filter_date) . "'";
}
if (count($where) > 0) {
    $sql .= " WHERE " . implode(" AND ", $where);
}

// Count total records
$totalResult = $conn->query($sql);
$totalRecords = $totalResult->num_rows;
$totalPages = ceil($totalRecords / $limit);

// Add LIMIT for current page
$sql .= " ORDER BY f.id DESC LIMIT $start, $limit";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Fault Stock View</title>
    <link rel="icon" type="image/png" href="assets/logo/logo_icon.png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { display: flex; flex-direction: column; min-height: 100vh; }
        .flex-grow-1 { flex: 1; }
        footer { background: #f8f9fa; padding: 10px 0; }
    </style>
</head>
<body class="bg-light">

<!-- Navbar -->
<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
include 'navbar.php';
?>

<div class="flex-grow-1">
    <div class="container mt-2">
        <h2 class="mb-3 text-center text-danger">Fault Stock View</h2>
        <div class="d-flex justify-content-center">
            <!-- Filter Form -->
            <form method="GET" class="row g-3 mb-4">
                <div class="col-md-3">
                    <input type="text" class="form-control" name="item_name" placeholder="Filter by Item" value="<?php echo htmlspecialchars($filter_item); ?>">
                </div>
                <div class="col-md-3">
                    <input type="text" class="form-control" name="given_to" placeholder="Filter by Given To" value="<?php echo htmlspecialchars($filter_given_to); ?>">
                </div>
                <div class="col-md-3">
                    <input type="date" class="form-control" name="fault_date" value="<?php echo htmlspecialchars($filter_date); ?>">
                </div>
                <div class="col-md-3 d-flex gap-2">
                    <button class="btn btn-danger" type="submit">Filter</button>
                    <a href="fault_view.php" class="btn btn-secondary">Reset</a>
                </div>
            </form>
        </div>
        <!-- Fault Table -->
        <table class="table table-bordered table-striped shadow-sm">
            <thead class="table-dark text-center">
                <tr>
                    <th>ID</th>
                    <th>Invoice Number</th>
                    <th>Fault Date</th>
                    <th>Given To</th>
                    <th>Item</th>
                    <th>Particular</th>
                    <th>Specification</th>
                    <th>Model</th>
                    <th>Qty</th>
                    <th>Remarks</th>
                </tr>
            </thead>

            <tbody>
                <?php 
                if ($result && $result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                        echo "<tr>
                            <td>".htmlspecialchars($row['id'])."</td>
                            <td>".($row['invoice_number'] ?: 'N/A')."</td>
                            <td>".htmlspecialchars($row['fault_date'])."</td>
                            <td>".htmlspecialchars($row['given_to'])."</td>
                            <td>".htmlspecialchars($row['item_name'])."</td>
                            <td>".($row['particular_name'] ?: '0')."</td>
                            <td>".($row['specification'] ?: '0')."</td>
                            <td>".($row['model_number'] ?: '0')."</td>
                            <td>".($row['qty'] ?: '0')."</td>
                            <td>".htmlspecialchars($row['remarks'])."</td>
                        </tr>";
                    }
                } else {
                    echo "<tr><td colspan='10' class='text-center text-danger'>No records found</td></tr>";
                }
                ?>
            </tbody>
        </table>

        <!-- Pagination -->
        <?php
        $queryString = "";
        if ($filter_item) $queryString .= "&item_name=".urlencode($filter_item);
        if ($filter_given_to) $queryString .= "&given_to=".urlencode($filter_given_to);
        if ($filter_date) $queryString .= "&fault_date=".urlencode($filter_date);
        ?>

        <?php if($totalPages > 1): ?>
        <div class="d-flex justify-content-center mt-3">
            <ul class="pagination">
                <li class="page-item <?php if($page <= 1) echo 'disabled'; ?>">
                    <a class="page-link" href="?page=<?php echo max(1, $page-1).$queryString; ?>">Previous</a>
                </li>
                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <li class="page-item <?php if ($page == $i) echo 'active'; ?>">
                        <a class="page-link" href="?page=<?php echo $i.$queryString; ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>
                <li class="page-item <?php if($page >= $totalPages) echo 'disabled'; ?>">
                    <a class="page-link" href="?page=<?php echo min($totalPages, $page+1).$queryString; ?>">Next</a>
                </li>
            </ul>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php
if (session_status() == PHP_SESSION_NONE) session_start();
include 'footer.php';
?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
