<?php
// config.php ko shaamil karein, jo session aur database connection ko sambhalega.
require_once 'config.php';

// Yeh function jaanch karega ki user ke paas zaroori role hai ya nahi.
if (!function_exists('userHasRole')) {
    function userHasRole($required_roles) {
        if (!isset($_SESSION['user_roles'])) return false;
        if (!is_array($required_roles)) {
            $required_roles = [$required_roles];
        }
        return count(array_intersect($required_roles, $_SESSION['user_roles'])) > 0;
    }
}

// Suraksha jaanch: Sirf zaroori roles waale users hi is page ko access kar sakte hain.
if (!userHasRole(['Admin', 'Manager', 'SMM', 'Sales'])) {
    header('Location: dashboard.php');
    exit();
}

require_once 'header.php';

// --- FILTER LOGIC ---
$client_filter = $_GET['client_id'] ?? 'all';
$start_date_filter = $_GET['start_date'] ?? '';
$end_date_filter = $_GET['end_date'] ?? '';

$where_clauses = [];
$params = [];
$param_types = '';

if ($client_filter !== 'all' && is_numeric($client_filter)) {
    $where_clauses[] = "i.client_id = ?";
    $params[] = $client_filter;
    $param_types .= 'i';
}
if (!empty($start_date_filter)) {
    $where_clauses[] = "i.invoice_date >= ?";
    $params[] = $start_date_filter;
    $param_types .= 's';
}
if (!empty($end_date_filter)) {
    $where_clauses[] = "i.invoice_date <= ?";
    $params[] = $end_date_filter;
    $param_types .= 's';
}

$where_sql = '';
if (!empty($where_clauses)) {
    $where_sql = 'WHERE ' . implode(' AND ', $where_clauses);
}

// --- DATA FETCHING ---

// Summary Cards Data
$summary_sql = "SELECT SUM(total_amount) as total_revenue, SUM(amount_paid) as total_paid FROM invoices i $where_sql";
$stmt_summary = $conn->prepare($summary_sql);
if (!empty($params)) {
    $stmt_summary->bind_param($param_types, ...$params);
}
$stmt_summary->execute();
$summary_result = $stmt_summary->get_result()->fetch_assoc();
$total_revenue = $summary_result['total_revenue'] ?? 0;
$total_paid = $summary_result['total_paid'] ?? 0;
$total_due = $total_revenue - $total_paid;
$stmt_summary->close();

// Invoice List Data
$invoices_sql = "SELECT i.*, c.name as client_name_from_table FROM invoices i LEFT JOIN clients c ON i.client_id = c.id $where_sql ORDER BY i.invoice_date DESC, i.id DESC";
$stmt_invoices = $conn->prepare($invoices_sql);
if (!empty($params)) {
    $stmt_invoices->bind_param($param_types, ...$params);
}
$stmt_invoices->execute();
$invoices_result = $stmt_invoices->get_result();
$invoices = $invoices_result->fetch_all(MYSQLI_ASSOC);
$stmt_invoices->close();

// Clients for filter dropdown
$clients_result = $conn->query("SELECT id, name FROM clients ORDER BY name ASC");
$clients = $clients_result->fetch_all(MYSQLI_ASSOC);

?>
<title>Invoicing Dashboard - Digify OS</title>

<div class="p-6 md:p-10">
    <header class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold text-gray-800">Invoicing Dashboard</h2>
        <a href="create-invoice.php" class="px-5 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700">+ Create New Invoice</a>
    </header>

    <!-- Filter Section -->
    <div class="bg-white p-4 rounded-lg shadow-md mb-8 sticky top-0 z-10">
        <form method="GET" action="invoices.php">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-end">
                <div>
                    <label for="client_id" class="text-sm font-medium text-gray-700">Client</label>
                    <select name="client_id" id="client_id" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                        <option value="all">All Clients</option>
                        <?php foreach ($clients as $client): ?>
                            <option value="<?php echo $client['id']; ?>" <?php if ($client_filter == $client['id']) echo 'selected'; ?>>
                                <?php echo htmlspecialchars($client['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="start_date" class="text-sm font-medium text-gray-700">Start Date</label>
                    <input type="date" name="start_date" id="start_date" value="<?php echo htmlspecialchars($start_date_filter); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                </div>
                <div>
                    <label for="end_date" class="text-sm font-medium text-gray-700">End Date</label>
                    <input type="date" name="end_date" id="end_date" value="<?php echo htmlspecialchars($end_date_filter); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                </div>
                <div class="flex items-center space-x-2">
                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700">Filter</button>
                    <a href="invoices.php" class="px-4 py-2 text-sm text-gray-600 hover:underline">Reset</a>
                </div>
            </div>
        </form>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div class="bg-blue-100 p-6 rounded-lg shadow-md">
            <h3 class="text-sm font-semibold text-blue-800">TOTAL REVENUE</h3>
            <p class="text-3xl font-bold text-blue-900 mt-2">₹<?php echo number_format($total_revenue, 2); ?></p>
        </div>
        <div class="bg-green-100 p-6 rounded-lg shadow-md">
            <h3 class="text-sm font-semibold text-green-800">TOTAL PAID</h3>
            <p class="text-3xl font-bold text-green-900 mt-2">₹<?php echo number_format($total_paid, 2); ?></p>
        </div>
        <div class="bg-red-100 p-6 rounded-lg shadow-md">
            <h3 class="text-sm font-semibold text-red-800">TOTAL DUE</h3>
            <p class="text-3xl font-bold text-red-900 mt-2">₹<?php echo number_format($total_due, 2); ?></p>
        </div>
    </div>

    <!-- Invoice List -->
    <div class="bg-white rounded-lg shadow-lg overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full">
                <thead class="bg-gray-100">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Invoice ID</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Client</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Invoice Date</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Due Date</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Total Amount</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Amount Paid</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($invoices)): ?>
                        <tr><td colspan="8" class="px-6 py-10 text-center text-gray-500">No invoices found for the selected criteria.</td></tr>
                    <?php else: ?>
                        <?php foreach ($invoices as $invoice): ?>
                            <?php $balance = $invoice['total_amount'] - $invoice['amount_paid']; ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">#<?php echo htmlspecialchars(str_pad($invoice['id'], 4, '0', STR_PAD_LEFT)); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700"><?php echo htmlspecialchars($invoice['client_name']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600"><?php echo date("d M, Y", strtotime($invoice['invoice_date'])); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600"><?php echo date("d M, Y", strtotime($invoice['due_date'])); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-800 font-semibold">₹<?php echo number_format($invoice['total_amount'], 2); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-green-700">₹<?php echo number_format($invoice['amount_paid'], 2); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm">
                                    <?php
                                        $status = htmlspecialchars($invoice['status']);
                                        $status_color = 'bg-yellow-100 text-yellow-800';
                                        if ($status == 'Paid') {
                                            $status_color = 'bg-green-100 text-green-800';
                                        } elseif ($balance > 0 && strtotime($invoice['due_date']) < time()) {
                                            $status = 'Overdue';
                                            $status_color = 'bg-red-100 text-red-800';
                                        }
                                    ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $status_color; ?>">
                                        <?php echo $status; ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <a href="view-invoice.php?id=<?php echo $invoice['id']; ?>" class="text-indigo-600 hover:text-indigo-900">View</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once 'footer.php'; ?>

