<?php
session_start();
require_once("../config/config.php");

// Allowed roles
$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

// Date Range Filter
$from_date = $_GET['from_date'] ?? date('Y-m-01');
$to_date   = $_GET['to_date']   ?? date('Y-m-d');

// Export CSV
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="Enquiry_Offer_Report_' . date('Ymd') . '.csv"');

    $output = fopen("php://output", "w");
    fputcsv($output, ['Enquiry Code', 'Customer Name', 'Mobile', 'Enquiry Date', 'Total Offers', 'Accepted', 'Pending', 'Rejected']);

    $query = "
        SELECT 
            e.enquiry_code,
            e.name AS customer_name,
            e.mobile,
            e.enquiry_date,
            COUNT(o.id) AS total_offers,
            SUM(CASE WHEN o.status = 'Accepted' THEN 1 ELSE 0 END) AS accepted,
            SUM(CASE WHEN o.status = 'Pending' THEN 1 ELSE 0 END) AS pending,
            SUM(CASE WHEN o.status = 'Rejected' THEN 1 ELSE 0 END) AS rejected
        FROM enquiry_master e
        LEFT JOIN offer_master o ON e.id = o.enquiry_id
        WHERE e.enquiry_date BETWEEN ? AND ?
        GROUP BY e.id
        ORDER BY e.enquiry_date DESC";

    $stmt = $conn->prepare($query);
    $stmt->bind_param("ss", $from_date, $to_date);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        fputcsv($output, [
            $row['enquiry_code'],
            $row['customer_name'],
            $row['mobile'],
            $row['enquiry_date'],
            $row['total_offers'],
            $row['accepted'],
            $row['pending'],
            $row['rejected']
        ]);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enquiry & Offer Report</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.10);
            --glass-border: rgba(255,255,255,0.20);
        }

        * { margin:0; padding:0; box-sizing:border-box; }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), 
                        url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }

        .container { max-width: 1350px; margin: auto; }

        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 25px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
            padding: 50px 40px;
            text-align: center;
        }
        .header h1 {
            font-size: clamp(28px, 5vw, 42px);
            font-weight: 700;
        }

        .filter-bar {
            padding: 25px 40px;
            background: rgba(255,255,255,0.05);
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
        }

        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            padding: 40px;
        }

        .summary-card {
            background: rgba(255,255,255,0.08);
            border-radius: 20px;
            padding: 25px;
            text-align: center;
            border: 1px solid rgba(255,255,255,0.15);
        }

        .summary-card h3 { 
            font-size: 2.4rem; 
            margin: 10px 0; 
            color: #c4b5fd; 
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 0 40px 40px;
        }
        th, td {
            padding: 16px;
            text-align: left;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        th { 
            background: rgba(168,85,247,0.3); 
            font-weight: 600;
        }
        
        input{
            padding: 8px 18px;
            border-radius: 50px;
            border: none;
            background: rgba(255,255,255,0.15);
            color: white;
            font-size: 0.9rem;
            font-weight: 700;
        }
        .status {
            padding: 8px 18px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 700;
        }

        .export-btn {
            background: linear-gradient(135deg, #22c55e, #86efac);
            color: #052e16;
            padding: 12px 28px;
            border-radius: 16px;
            text-decoration: none;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }

        @media (max-width: 768px) {
            .glass-container { border-radius: 24px; }
            .filter-bar, .summary-grid { padding: 20px; }
        }
    </style>
</head>
<body>

<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">

        <div class="header">
            <h1><i class="fas fa-chart-bar"></i> Enquiry & Offer Report</h1>
            <p style="margin-top:12px; opacity:0.9;">Detailed Performance Analysis</p>
        </div>

        <!-- Filter Bar -->
        <div class="filter-bar">
            <form method="GET">
                <label>From Date</label>
                <input type="date" name="from_date" value="<?= htmlspecialchars($from_date) ?>">

                <label>To Date</label>
                <input type="date" name="to_date" value="<?= htmlspecialchars($to_date) ?>">

                <button type="submit" style="padding:12px 28px; background:var(--primary); color:white; border:none; border-radius:16px; cursor:pointer;">
                    <i class="fas fa-filter"></i> Generate Report
                </button>
            </form>

            <a href="?from_date=<?= urlencode($from_date) ?>&to_date=<?= urlencode($to_date) ?>&export=csv" 
               class="export-btn" target="_blank">
                <i class="fas fa-file-export"></i> Export to CSV
            </a>
        </div>

        <!-- Summary Cards -->
        <div class="summary-grid">
            <?php
            // Total Enquiries
            $total_enq = $conn->query("SELECT COUNT(*) as cnt FROM enquiry_master 
                                      WHERE enquiry_date BETWEEN '$from_date' AND '$to_date'")->fetch_assoc()['cnt'];

            // Total Offers
            $total_off = $conn->query("SELECT COUNT(*) as cnt FROM offer_master 
                                      WHERE offer_date BETWEEN '$from_date' AND '$to_date'")->fetch_assoc()['cnt'];

            // Accepted Offers
            $accepted = $conn->query("SELECT COUNT(*) as cnt FROM offer_master 
                                     WHERE status = 'Accepted' AND offer_date BETWEEN '$from_date' AND '$to_date'")->fetch_assoc()['cnt'];

            $conversion = $total_off > 0 ? round(($accepted / $total_off) * 100, 2) : 0;
            ?>
            <div class="summary-card">
                <h3><?= $total_enq ?></h3>
                <p>Total Enquiries</p>
            </div>
            <div class="summary-card">
                <h3><?= $total_off ?></h3>
                <p>Total Offers Generated</p>
            </div>
            <div class="summary-card">
                <h3><?= $accepted ?></h3>
                <p>Accepted Offers</p>
            </div>
            <div class="summary-card">
                <h3><?= $conversion ?>%</h3>
                <p>Conversion Rate</p>
            </div>
        </div>

        <!-- Enquiry-wise Offer Report -->
        <h2 style="margin:0 40px 15px; color:#ddd6fe;">Enquiry-wise Offer Report</h2>
        <table>
            <thead>
                <tr>
                    <th>Enquiry Code</th>
                    <th>Customer Name</th>
                    <th>Mobile</th>
                    <th>Enquiry Date</th>
                    <th>Total Offers</th>
                    <th>Accepted</th>
                    <th>Pending</th>
                    <th>Rejected</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $report_query = "
                    SELECT 
                        e.enquiry_code,
                        e.name AS customer_name,
                        e.mobile,
                        e.enquiry_date,
                        COUNT(o.id) AS total_offers,
                        SUM(CASE WHEN o.status = 'Accepted' THEN 1 ELSE 0 END) AS accepted,
                        SUM(CASE WHEN o.status = 'Pending' THEN 1 ELSE 0 END) AS pending,
                        SUM(CASE WHEN o.status = 'Rejected' THEN 1 ELSE 0 END) AS rejected
                    FROM enquiry_master e
                    LEFT JOIN offer_master o ON e.id = o.enquiry_id
                    WHERE e.enquiry_date BETWEEN ? AND ?
                    GROUP BY e.id
                    ORDER BY e.enquiry_date DESC";

                $stmt = $conn->prepare($report_query);
                $stmt->bind_param("ss", $from_date, $to_date);
                $stmt->execute();
                $report_result = $stmt->get_result();

                while ($row = $report_result->fetch_assoc()): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($row['enquiry_code']) ?></strong></td>
                    <td><?= htmlspecialchars($row['customer_name']) ?></td>
                    <td><?= htmlspecialchars($row['mobile']) ?></td>
                    <td><?= date('d M Y', strtotime($row['enquiry_date'])) ?></td>
                    <td><strong><?= $row['total_offers'] ?></strong></td>
                    <td><?= $row['accepted'] ?></td>
                    <td><?= $row['pending'] ?></td>
                    <td><?= $row['rejected'] ?></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>

<?php $conn->close(); ?>