<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Initialize QuotationManager
require_once 'QuotationManager.php';
$quotationManager = new QuotationManager($conn, $_SESSION['user_id'], $_SESSION['role_id']);

// Get quotation filters from query parameters
$status = $_GET['status'] ?? 'all';
$period = $_GET['period'] ?? 'month';
$search = $_GET['search'] ?? '';

// Determine date range based on period
$end_date = date('Y-m-d');
switch ($period) {
    case 'week':
        $start_date = date('Y-m-d', strtotime('-1 week'));
        break;
    case 'month':
        $start_date = date('Y-m-d', strtotime('-1 month'));
        break;
    case 'quarter':
        $start_date = date('Y-m-d', strtotime('-3 months'));
        break;
    case 'year':
        $start_date = date('Y-m-d', strtotime('-1 year'));
        break;
    default:
        $start_date = date('Y-m-d', strtotime('-1 month'));
}

// Fetch all quotations
$sql = "SELECT q.*, c.corporate, u.full_name as created_by_name
        FROM quotations q
        JOIN corporate c ON q.corp_id = c.corp_id
        JOIN users u ON q.generated_by = u.user_id
        WHERE q.generated_at BETWEEN ? AND ?";

$params = [$start_date, $end_date];
$types = 'ss';

// Add status filter if not 'all'
if ($status !== 'all') {
    $sql .= " AND q.status = ?";
    $params[] = $status;
    $types .= 's';
}

// Add search term if provided
if (!empty($search)) {
    $sql .= " AND (q.quotation_no LIKE ? OR c.corporate LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $types .= 'ss';
}

$sql .= " ORDER BY q.generated_at DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
$quotations = $result->fetch_all(MYSQLI_ASSOC);

// Get quotation statistics
$sql = "SELECT 
        COUNT(*) as total_quotations,
        SUM(CASE WHEN status = 'CONVERTED' THEN 1 ELSE 0 END) as converted,
        SUM(CASE WHEN status IN ('EXPIRED', 'REJECTED', 'DISCOUNT_REJECTED') THEN 1 ELSE 0 END) as lost,
        SUM(CASE WHEN status IN ('PENDING', 'PENDING_APPROVAL', 'APPROVED') THEN 1 ELSE 0 END) as pending,
        SUM(total_premium) as total_quoted_premium,
        SUM(CASE WHEN status = 'CONVERTED' THEN total_premium ELSE 0 END) as converted_premium
        FROM quotations
        WHERE generated_at BETWEEN ? AND ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $start_date, $end_date);
$stmt->execute();
$stats = $stmt->get_result()->fetch_assoc();

// Calculate conversion rate
$conversion_rate = $stats['total_quotations'] > 0 ? 
    ($stats['converted'] / $stats['total_quotations']) * 100 : 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Quotation Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Sales', 'title' => 'Quotation Management')); ?>

                    <!-- Stats Row -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Total Quotations</p>
                                            <h4 class="fs-22 fw-semibold mb-0"><?php echo number_format($stats['total_quotations']); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-primary rounded fs-3">
                                                <i class="ri-file-list-3-line text-primary"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Conversion Rate</p>
                                            <h4 class="fs-22 fw-semibold mb-0"><?php echo number_format($conversion_rate, 1); ?>%</h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-success rounded fs-3">
                                                <i class="ri-arrow-right-up-line text-success"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Total Premium</p>
                                            <h4 class="fs-22 fw-semibold mb-0">KES <?php echo number_format($stats['total_quoted_premium']); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-info rounded fs-3">
                                                <i class="ri-money-dollar-circle-line text-info"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Converted Premium</p>
                                            <h4 class="fs-22 fw-semibold mb-0">KES <?php echo number_format($stats['converted_premium']); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning rounded fs-3">
                                                <i class="ri-wallet-3-line text-warning"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Controls -->
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Quotation List</h4>
                                    <div class="flex-shrink-0">
                                        <a href="create_quotation.php" class="btn btn-primary">
                                            <i class="ri-add-line align-bottom me-1"></i> Create Quotation
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <form action="" method="get" class="mb-3">
                                                <div class="input-group">
                                                    <input type="text" class="form-control" placeholder="Search quotations..." name="search" value="<?php echo htmlspecialchars($search); ?>">
                                                    <button class="btn btn-primary" type="submit">
                                                        <i class="ri-search-line"></i>
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                        <div class="col-md-3">
                                            <select class="form-select" id="statusFilter" onchange="updateFilters()">
                                                <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>All Status</option>
                                                <option value="PENDING" <?php echo $status === 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="PENDING_APPROVAL" <?php echo $status === 'PENDING_APPROVAL' ? 'selected' : ''; ?>>Pending Approval</option>
                                                <option value="APPROVED" <?php echo $status === 'APPROVED' ? 'selected' : ''; ?>>Approved</option>
                                                <option value="CONVERTED" <?php echo $status === 'CONVERTED' ? 'selected' : ''; ?>>Converted</option>
                                                <option value="EXPIRED" <?php echo $status === 'EXPIRED' ? 'selected' : ''; ?>>Expired</option>
                                                <option value="REJECTED" <?php echo $status === 'REJECTED' ? 'selected' : ''; ?>>Rejected</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <select class="form-select" id="periodFilter" onchange="updateFilters()">
                                                <option value="week" <?php echo $period === 'week' ? 'selected' : ''; ?>>Last Week</option>
                                                <option value="month" <?php echo $period === 'month' ? 'selected' : ''; ?>>Last Month</option>
                                                <option value="quarter" <?php echo $period === 'quarter' ? 'selected' : ''; ?>>Last Quarter</option>
                                                <option value="year" <?php echo $period === 'year' ? 'selected' : ''; ?>>Last Year</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <a href="quotation_report.php" class="btn btn-secondary w-100">
                                                <i class="ri-bar-chart-line align-bottom me-1"></i> Reports
                                            </a>
                                        </div>
                                    </div>

                                    <div class="table-responsive">
                                        <table class="table table-bordered align-middle table-nowrap mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Quotation #</th>
                                                    <th>Corporate</th>
                                                    <th>Date</th>
                                                    <th>Type</th>
                                                    <th>Premium</th>
                                                    <th>Status</th>
                                                    <th>Created By</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($quotations as $quote): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($quote['quotation_no']); ?></td>
                                                    <td><?php echo htmlspecialchars($quote['corporate']); ?></td>
                                                    <td><?php echo date('d M Y', strtotime($quote['generated_at'])); ?></td>
                                                    <td><?php echo htmlspecialchars($quote['quotation_type']); ?></td>
                                                    <td>KES <?php echo number_format($quote['total_premium'], 2); ?></td>
                                                    <td>
                                                        <?php 
                                                        $status_class = 'bg-info';
                                                        switch ($quote['status']) {
                                                            case 'PENDING':
                                                                $status_class = 'bg-warning';
                                                                break;
                                                            case 'PENDING_APPROVAL':
                                                                $status_class = 'bg-warning';
                                                                break;
                                                            case 'APPROVED':
                                                                $status_class = 'bg-success';
                                                                break;
                                                            case 'CONVERTED':
                                                                $status_class = 'bg-primary';
                                                                break;
                                                            case 'EXPIRED':
                                                                $status_class = 'bg-secondary';
                                                                break;
                                                            case 'REJECTED':
                                                            case 'DISCOUNT_REJECTED':
                                                                $status_class = 'bg-danger';
                                                                break;
                                                        }
                                                        ?>
                                                        <span class="badge <?php echo $status_class; ?>">
                                                            <?php echo htmlspecialchars($quote['status']); ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($quote['created_by_name']); ?></td>
                                                    <td>
                                                        <div class="dropdown">
                                                            <a href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
                                                                <i class="ri-more-2-fill"></i>
                                                            </a>
                                                            <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
                                                                <li>
                                                                    <a class="dropdown-item" href="view_quotation.php?id=<?php echo $quote['quotation_no']; ?>">
                                                                        <i class="ri-eye-line align-bottom me-2 text-muted"></i> View Details
                                                                    </a>
                                                                </li>
                                                                <?php if ($quote['status'] === 'PENDING' || $quote['status'] === 'APPROVED'): ?>
                                                                <li>
                                                                    <a class="dropdown-item" href="revise_quotation.php?id=<?php echo $quote['quotation_no']; ?>">
                                                                        <i class="ri-edit-2-line align-bottom me-2 text-muted"></i> Revise
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                                <?php if (($quote['status'] === 'PENDING' || $quote['status'] === 'APPROVED') && $_SESSION['role_id'] == 1): ?>
                                                                <li>
                                                                    <a class="dropdown-item" href="convert_quotation.php?id=<?php echo $quote['quotation_no']; ?>">
                                                                        <i class="ri-check-double-line align-bottom me-2 text-muted"></i> Convert to Policy
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                                <?php if ($quote['status'] === 'PENDING_APPROVAL' && ($_SESSION['role_id'] == 1 || $_SESSION['role_id'] == 2)): ?>
                                                                <li>
                                                                    <a class="dropdown-item" href="discount_approval.php?id=<?php echo $quote['quotation_no']; ?>">
                                                                        <i class="ri-thumb-up-line align-bottom me-2 text-muted"></i> Approve Discount
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                                <?php if ($quote['status'] === 'PENDING' && ($quote['generated_by'] == $_SESSION['user_id'] || $_SESSION['role_id'] == 1)): ?>
                                                                <li>
                                                                    <a class="dropdown-item" href="edit_quotation.php?id=<?php echo $quote['quotation_no']; ?>">
                                                                        <i class="ri-pencil-line align-bottom me-2 text-muted"></i> Edit
                                                                    </a>
                                                                </li>
                                                                <?php endif; ?>
                                                                <li>
                                                                    <a class="dropdown-item" href="print_quotation.php?id=<?php echo $quote['quotation_no']; ?>" target="_blank">
                                                                        <i class="ri-printer-line align-bottom me-2 text-muted"></i> Print
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item" href="email_quotation.php?id=<?php echo $quote['quotation_no']; ?>">
                                                                        <i class="ri-mail-send-line align-bottom me-2 text-muted"></i> Email
                                                                    </a>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                                <?php if (empty($quotations)): ?>
                                                <tr>
                                                    <td colspan="8" class="text-center">No quotations found</td>
                                                </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        function updateFilters() {
            const status = document.getElementById('statusFilter').value;
            const period = document.getElementById('periodFilter').value;
            const searchParams = new URLSearchParams(window.location.search);
            
            searchParams.set('status', status);
            searchParams.set('period', period);
            
            // Preserve search term if it exists
            if (searchParams.has('search')) {
                const search = searchParams.get('search');
                if (search) {
                    searchParams.set('search', search);
                }
            }
            
            window.location.href = window.location.pathname + '?' + searchParams.toString();
        }
    </script>
</body>
</html>