<?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 LeadTracker
require_once 'LeadTracker.php';
$leadTracker = new LeadTracker($conn, $_SESSION['user_id'], $_SESSION['role_id']);

// Get upcoming tasks for current user
$tasksResult = $leadTracker->getUpcomingTasks($_SESSION['user_id']);
$tasks = $tasksResult['success'] ? $tasksResult['data']['tasks'] : [];
$tasksByDate = $tasksResult['success'] ? $tasksResult['data']['grouped_by_date'] : [];

// Get leads statistics
$leadsResult = $leadTracker->getLeads();
$leadsStats = $leadsResult['success'] ? $leadsResult['data']['stats'] : [];

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

// Get quotation conversion statistics for current user
$startDate = date('Y-m-d', strtotime('-90 days'));
$endDate = date('Y-m-d');
$conversionStats = $quotationManager->getConversionStatistics($startDate, $endDate, $_SESSION['user_id']);
$conversionData = $conversionStats['success'] ? $conversionStats['data'] : [];

// Get recent quotations - this is a custom query since the method doesn't exist
$sql = "SELECT q.*, c.corporate 
        FROM quotations q
        JOIN corporate c ON q.corp_id = c.corp_id
        WHERE q.generated_by = ?
        ORDER BY q.generated_at DESC
        LIMIT 5";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_SESSION['user_id']);
$stmt->execute();
$recentQuotations = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Sales Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Apex Charts -->
    <link href="assets/libs/apexcharts/apexcharts.min.css" rel="stylesheet">
</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 & Distribution', 'title' => 'Dashboard')); ?>

                    <!-- Key metrics 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 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Active Leads</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <span class="counter-value" data-target="<?php echo isset($leadsStats['total_leads']) ? $leadsStats['total_leads'] - ($leadsStats['won_leads'] + $leadsStats['lost_leads']) : 0; ?>">0</span>
                                            </h4>
                                            <a href="leads_list.php" class="text-decoration-underline">View all leads</a>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-primary-subtle rounded fs-3">
                                                <i class="bx bx-user-voice 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 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Pending Tasks</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <span class="counter-value" data-target="<?php echo count($tasks); ?>">0</span>
                                            </h4>
                                            <a href="task_calendar.php" class="text-decoration-underline">View calendar</a>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-info-subtle rounded fs-3">
                                                <i class="bx bx-task 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 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Conversion Rate</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <span class="counter-value" data-target="<?php echo isset($conversionData['overall']['conversion_rate']) ? round($conversionData['overall']['conversion_rate']) : 0; ?>">0</span>%
                                            </h4>
                                            <a href="quotation_reports.php" class="text-decoration-underline">View reports</a>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-success-subtle rounded fs-3">
                                                <i class="bx bx-trending-up 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 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Business Potential</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <span class="counter-value" data-target="<?php echo isset($leadsStats['total_potential']) ? round($leadsStats['total_potential']) : 0; ?>">0</span>
                                            </h4>
                                            <a href="leads_list.php?filter=qualified" class="text-decoration-underline">View qualified leads</a>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-warning-subtle rounded fs-3">
                                                <i class="bx bx-money text-warning"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Middle section with calendar and conversion chart -->
                    <div class="row">
                        <!-- Upcoming Tasks Calendar -->
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Upcoming Tasks</h4>
                                    <div class="flex-shrink-0">
                                        <a href="task_calendar.php" class="btn btn-soft-primary btn-sm">
                                            <i class="ri-calendar-event-line align-middle"></i> Full Calendar
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <?php if (empty($tasks)): ?>
                                        <div class="text-center p-4">
                                            <div class="avatar-md mx-auto mb-4">
                                                <div class="avatar-title bg-light rounded-circle text-primary">
                                                    <i class="ri-task-line fs-24"></i>
                                                </div>
                                            </div>
                                            <p class="text-muted mb-4">No upcoming tasks found</p>
                                            <a href="add_task.php" class="btn btn-soft-success btn-sm">
                                                <i class="ri-add-line align-middle"></i> Create New Task
                                            </a>
                                        </div>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-borderless table-nowrap">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th scope="col">Date</th>
                                                        <th scope="col">Task</th>
                                                        <th scope="col">Lead</th>
                                                        <th scope="col">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach (array_slice($tasks, 0, 5) as $task): ?>
                                                    <tr>
                                                        <td><?php echo date('d M', strtotime($task['task_date'])); ?></td>
                                                        <td>
                                                            <span class="badge bg-<?php echo $task['task_type'] == 'CALL' ? 'warning' : ($task['task_type'] == 'MEETING' ? 'primary' : 'info'); ?> me-1">
                                                                <?php echo $task['task_type']; ?>
                                                            </span>
                                                            <?php echo $task['description']; ?>
                                                        </td>
                                                        <td>
                                                            <a href="lead_details.php?id=<?php echo $task['lead_id']; ?>" class="fw-medium">
                                                                <?php echo $task['client_name']; ?>
                                                            </a>
                                                        </td>
                                                        <td>
                                                            <a href="complete_task.php?id=<?php echo $task['task_id']; ?>" class="btn btn-sm btn-soft-success">
                                                                Complete
                                                            </a>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Conversion Chart -->
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Conversion Analytics</h4>
                                    <div class="flex-shrink-0">
                                        <button type="button" class="btn btn-soft-info btn-sm">
                                            <i class="ri-file-list-3-line align-middle"></i> Report
                                        </button>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <div id="conversion_chart" class="apex-charts" dir="ltr"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Bottom row with recent quotations and sales pipeline -->
                    <div class="row">
                        <!-- Recent Quotations -->
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Recent Quotations</h4>
                                    <div class="flex-shrink-0">
                                        <a href="create_quotation.php" class="btn btn-soft-primary btn-sm">
                                            <i class="ri-add-line align-middle"></i> New Quotation
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <?php if (empty($recentQuotations)): ?>
                                        <div class="text-center p-4">
                                            <div class="avatar-md mx-auto mb-4">
                                                <div class="avatar-title bg-light rounded-circle text-primary">
                                                    <i class="ri-file-list-3-line fs-24"></i>
                                                </div>
                                            </div>
                                            <p class="text-muted mb-4">No quotations found</p>
                                            <a href="create_quotation.php" class="btn btn-soft-success btn-sm">
                                                <i class="ri-add-line align-middle"></i> Create First Quotation
                                            </a>
                                        </div>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-borderless table-nowrap">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th scope="col">Quotation #</th>
                                                        <th scope="col">Corporate</th>
                                                        <th scope="col">Date</th>
                                                        <th scope="col">Status</th>
                                                        <th scope="col">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($recentQuotations as $quote): ?>
                                                    <tr>
                                                        <td>
                                                            <a href="view_quotation.php?no=<?php echo $quote['quotation_no']; ?>" class="fw-medium">
                                                                <?php echo $quote['quotation_no']; ?>
                                                            </a>
                                                        </td>
                                                        <td><?php echo $quote['corporate']; ?></td>
                                                        <td><?php echo date('d M Y', strtotime($quote['generated_at'])); ?></td>
                                                        <td>
                                                            <?php
                                                            $statusClass = 'info';
                                                            if ($quote['status'] == 'APPROVED' || $quote['status'] == 'CONVERTED') {
                                                                $statusClass = 'success';
                                                            } elseif ($quote['status'] == 'PENDING_APPROVAL') {
                                                                $statusClass = 'warning';
                                                            } elseif ($quote['status'] == 'REJECTED' || $quote['status'] == 'DISCOUNT_REJECTED' || $quote['status'] == 'EXPIRED') {
                                                                $statusClass = 'danger';
                                                            }
                                                            ?>
                                                            <span class="badge bg-<?php echo $statusClass; ?>">
                                                                <?php echo $quote['status']; ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <div class="dropdown">
                                                                <a href="#" role="button" id="dropdownMenuLink1" data-bs-toggle="dropdown" aria-expanded="false">
                                                                    <i class="ri-more-2-fill"></i>
                                                                </a>
                                                                <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink1">
                                                                    <li><a class="dropdown-item" href="view_quotation.php?no=<?php echo $quote['quotation_no']; ?>">View</a></li>
                                                                    <?php if ($quote['status'] == 'APPROVED'): ?>
                                                                    <li><a class="dropdown-item" href="convert_to_policy.php?no=<?php echo $quote['quotation_no']; ?>">Convert to Policy</a></li>
                                                                    <?php endif; ?>
                                                                    <li><a class="dropdown-item" href="edit_quotation.php?no=<?php echo $quote['quotation_no']; ?>">Edit</a></li>
                                                                    <li><a class="dropdown-item" href="quotation_pdf.php?no=<?php echo $quote['quotation_no']; ?>">Download PDF</a></li>
                                                                </ul>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Sales Pipeline -->
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Sales Pipeline</h4>
                                    <div class="flex-shrink-0">
                                        <a href="leads_list.php" class="btn btn-soft-primary btn-sm">
                                            View All
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <div id="sales_pipeline" class="apex-charts" dir="ltr"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/apexcharts/apexcharts.min.js"></script>
    <script src="assets/libs/countup.js/countUp.min.js"></script>
    <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>
        // Initialize CountUp
        document.addEventListener('DOMContentLoaded', function() {
            const counterElements = document.querySelectorAll('.counter-value');
            counterElements.forEach(function(element) {
                const target = parseFloat(element.getAttribute('data-target'));
                const countUp = new CountUp(element, target, {
                    duration: 2.5,
                    separator: ',',
                    decimal: '.'
                });
                countUp.start();
            });

            // Initialize Conversion Chart
            const conversionChartOptions = {
                series: [{
                    name: 'Quotations',
                    data: [
                        <?php 
                            if (isset($conversionData['by_month'])) {
                                $quotations = array_map(function($item) { 
                                    return $item['total']; 
                                }, $conversionData['by_month']);
                                echo implode(', ', $quotations);
                            } else {
                                echo "10, 15, 8, 12, 7, 16";
                            }
                        ?>
                    ]
                }, {
                    name: 'Converted',
                    data: [
                        <?php 
                            if (isset($conversionData['by_month'])) {
                                $converted = array_map(function($item) { 
                                    return $item['converted']; 
                                }, $conversionData['by_month']);
                                echo implode(', ', $converted);
                            } else {
                                echo "4, 6, 2, 8, 3, 7";
                            }
                        ?>
                    ]
                }],
                chart: {
                    height: 350,
                    type: 'bar',
                    toolbar: {
                        show: false,
                    }
                },
                plotOptions: {
                    bar: {
                        horizontal: false,
                        columnWidth: '55%',
                        endingShape: 'rounded'
                    },
                },
                dataLabels: {
                    enabled: false
                },
                stroke: {
                    show: true,
                    width: 2,
                    colors: ['transparent']
                },
                xaxis: {
                    categories: [
                        <?php 
                            if (isset($conversionData['by_month'])) {
                                $months = array_map(function($item) { 
                                    $date = DateTime::createFromFormat('Y-m', $item['month']);
                                    return "'" . $date->format('M Y') . "'"; 
                                }, $conversionData['by_month']);
                                echo implode(', ', $months);
                            } else {
                                echo "'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'";
                            }
                        ?>
                    ],
                },
                yaxis: {
                    title: {
                        text: 'Count'
                    }
                },
                fill: {
                    opacity: 1
                },
                tooltip: {
                    y: {
                        formatter: function (val) {
                            return val
                        }
                    }
                },
                colors: ['#405189', '#0ab39c']
            };

            const conversionChart = new ApexCharts(document.querySelector("#conversion_chart"), conversionChartOptions);
            conversionChart.render();
            
            // Initialize Sales Pipeline Chart
            const pipelineOptions = {
                series: [
                    <?php 
                        if (isset($leadsStats)) {
                            echo isset($leadsStats['new_leads']) ? $leadsStats['new_leads'] : 0 . ', ';
                            echo isset($leadsStats['qualified_leads']) ? $leadsStats['qualified_leads'] : 0 . ', ';
                            echo isset($leadsStats['proposal_leads']) ? $leadsStats['proposal_leads'] : 0 . ', ';
                            echo isset($leadsStats['negotiation_leads']) ? $leadsStats['negotiation_leads'] : 0;
                        } else {
                            echo "10, 15, 7, 12";
                        }
                    ?>
                ],
                chart: {
                    height: 350,
                    type: 'funnel',
                },
                plotOptions: {
                    bar: {
                        columnWidth: '65%',
                    }
                },
                colors: ['#405189', '#299cdb', '#0ab39c', '#f7b84b'],
                dataLabels: {
                    enabled: true,
                    formatter: function (val, opt) {
                        return opt.w.globals.labels[opt.dataPointIndex] + ": " + val
                    },
                    dropShadow: {
                        enabled: true,
                    }
                },
                labels: ['New', 'Qualified', 'Proposal', 'Negotiation'],
                title: {
                    text: 'Lead Status Distribution',
                    align: 'middle',
                }
            };

            const pipelineChart = new ApexCharts(document.querySelector("#sales_pipeline"), pipelineOptions);
            pipelineChart.render();
        });
    </script>
</body>
</html>