<?php

session_start();
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}
// Include the database connection from db.php
require_once '../config/db.php';

// Initialize filter values
$searchQuery = isset($_GET['search']) ? $_GET['search'] : '';
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : '';

// Build the SQL query with optional filters
$sql = "SELECT s.id, s.supply_date, s.total_cost, s.total_paid, sup.business_name 
        FROM supplies s 
        JOIN suppliers sup ON s.supplier_id = sup.id 
        WHERE (sup.business_name LIKE ? OR s.supply_date LIKE ?)";

if (!empty($startDate) && !empty($endDate)) {
    $sql .= " AND s.supply_date BETWEEN ? AND ?";
}

$sql .= " ORDER BY s.id DESC";
$stmt = $pdo->prepare($sql);
$searchTerm = '%' . $searchQuery . '%';
$params = [$searchTerm, $searchTerm];

if (!empty($startDate) && !empty($endDate)) {
    $params[] = $startDate;
    $params[] = $endDate;
}

$stmt->execute($params);
$supplies = $stmt->fetchAll();

// Calculate total sums
$totalCostSum = 0;
$totalPaidSum = 0;

foreach ($supplies as $supply) {
    $totalCostSum += $supply['total_cost'];
    $totalPaidSum += $supply['total_paid'];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Supplies - Store Management</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    
    <style>
        :root {
            --primary-color: #2c3e50;
            --border-color: #dee2e6;
            --text-color: #333333;
            --background-color: #f8f9fa;
        }

        body {
            background-color: var(--background-color);
            font-family: 'Mulish', sans-serif;
            color: var(--text-color);
        }

        .content {
            margin-left: 240px;
            padding: 20px;
        }

        .top-bar {
            background-color: #ffffff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        .supply-card {
            background: white;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            padding: 20px;
        }

        .summary-card {
            background: white;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 20px;
            text-align: center;
        }

        .table thead th {
            background-color: var(--primary-color);
            color: white;
        }

        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 10px;
            }
        }
    </style>
</head>
<body>
    <?php include '../includes/side_bar.php'; ?>

    <div class="content">
        <div class="top-bar">
            <div class="d-flex justify-content-between align-items-center">
                <h4 class="mb-0">Supply Records</h4>
                <div>
                    <a href="add_supply.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> New Supply
                    </a>
                    <a href="view_returns.php" class="btn btn-outline-primary">
                        <i class="fas fa-undo"></i> View Returns
                    </a>
                </div>
            </div>
        </div>

        <div class="supply-card">
            <form method="GET" class="row g-3">
                <div class="col-md-4">
                    <input type="text" name="search" class="form-control" 
                           placeholder="Search supplier or date" 
                           value="<?= htmlspecialchars($searchQuery) ?>">
                </div>
                <div class="col-md-3">
                    <input type="date" name="start_date" class="form-control" 
                           value="<?= htmlspecialchars($startDate) ?>">
                </div>
                <div class="col-md-3">
                    <input type="date" name="end_date" class="form-control" 
                           value="<?= htmlspecialchars($endDate) ?>">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-search"></i> Search
                    </button>
                </div>
            </form>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="summary-card">
                    <h6>Total Cost</h6>
                    <h4>₦<?= number_format($totalCostSum, 2) ?></h4>
                </div>
            </div>
            <div class="col-md-6">
                <div class="summary-card">
                    <h6>Total Paid</h6>
                    <h4>₦<?= number_format($totalPaidSum, 2) ?></h4>
                </div>
            </div>
        </div>

        <div class="supply-card">
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Supplier</th>
                            <th>Total Cost</th>
                            <th>Amount Paid</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($supplies)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-4">
                                    <i class="fas fa-box-open mb-3 fa-2x text-muted"></i>
                                    <p class="text-muted">No supplies found</p>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($supplies as $supply): 
                                $status = '';
                                if ($supply['total_paid'] >= $supply['total_cost']) {
                                    $status = '<span class="badge bg-success">Paid</span>';
                                } elseif ($supply['total_paid'] > 0) {
                                    $status = '<span class="badge bg-warning">Partial</span>';
                                } else {
                                    $status = '<span class="badge bg-danger">Unpaid</span>';
                                }
                            ?>
                                <tr>
                                    <td><?= htmlspecialchars(date('M d, Y', strtotime($supply['supply_date']))) ?></td>
                                    <td><?= htmlspecialchars($supply['business_name']) ?></td>
                                    <td>₦<?= number_format($supply['total_cost'], 2) ?></td>
                                    <td>₦<?= number_format($supply['total_paid'], 2) ?></td>
                                    <td><?= $status ?></td>
                                    <td>
                                        <a href="view_supply_details.php?id=<?= $supply['id'] ?>" 
                                           class="btn btn-sm btn-info">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="view_sup_pay.php?supply_id=<?= $supply['id'] ?>" 
                                           class="btn btn-sm btn-primary">
                                            <i class="fas fa-money-bill"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
</body>
</html>
