<?php
include 'db.php';
if (!isLoggedIn()) redirect('index.php');

$role = $_SESSION['role'];
?>
<?php include 'includes/header.php'; ?>
<body class="bg-gray-100 font-sans h-screen flex overflow-hidden">
    <?php include 'includes/sidebar.php'; ?>
    
    <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-50 p-4 md:p-8 pt-20 md:pt-8">
        <div class="flex justify-between items-center mb-8">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">Dashboard</h1>
                <p class="text-gray-500 mt-1">
                    <?= ($role === 'accounts') ? 'Financial Overview' : 'Overview of service status' ?> 
                    <?php if(isset($_GET['filter'])) echo ' - ' . ucfirst($_GET['filter']); ?>
                </p>
            </div>
            


            <!-- Date Filter Inputs & Buttons -->
             <div class="flex flex-col md:flex-row gap-2 items-center">
                <form action="" method="GET" class="flex items-center gap-2 bg-white p-1.5 rounded-lg border border-gray-200">
                    <span class="text-xs font-bold text-gray-500">From</span>
                    <input type="date" name="from_date" value="<?= $_GET['from_date'] ?? '' ?>" class="px-2 py-1 rounded border border-gray-300 text-sm focus:outline-none focus:border-indigo-500">
                    
                    <span class="text-xs font-bold text-gray-500">To</span>
                    <input type="date" name="to_date" value="<?= $_GET['to_date'] ?? '' ?>" class="px-2 py-1 rounded border border-gray-300 text-sm focus:outline-none focus:border-indigo-500">
                    
                    <button type="submit" class="bg-indigo-600 text-white px-3 py-1 rounded text-sm font-bold hover:bg-indigo-700">Filter</button>
                    <!-- Keep filter param if exists to maintain view mode if needed, though dates override usually -->
                </form>


            </div>
            
        </div>


        <!-- ACCOUNTS DASHBOARD -->
        <?php if ($role === 'accounts'): 
            // ... (Accounts Logic is fine, updated previously) ...
            // Just ensuring context matches for replacement if needed, 
            // but the chunk above ends at the closing div of "flex gap-2" section. 
            // I'll stick to the upper part replacement for UI. 
            // Wait, I need to update the Recent Tickets Query too which is further down.
            // I should duplicate the replace calls or use one large block? 
            // The instruction says "Update the Recent Tickets queries". That's a different location.
            // I will do two separate Replace calls to be safe and accurate.
        ?>
        <?php endif; ?>
        
        <?php // Wait, I cannot put PHP logic in valid HTML replacement if I am replacing the TOP part. ?>
        <?php // Let's split this into two tool calls. call 1: UI. call 2: Query. ?>
            
        </div>


        <!-- ACCOUNTS DASHBOARD -->
        <?php if ($role === 'accounts'): 
    // -------------------------------------------------------------------------
            // DATE FILTER LOGIC
            // -------------------------------------------------------------------------
            $filter_type = $_GET['filter'] ?? 'monthly';
            $input_from = $_GET['from_date'] ?? null;
            $input_to   = $_GET['to_date'] ?? null;

            // Default defaults (Monthly)
            $start_date = date('Y-m-01'); // First day of this month
            $end_date   = date('Y-m-t');  // Last day of this month

            if (!empty($input_from) && !empty($input_to)) {
                // User Custom Range
                $start_date = $input_from;
                $end_date   = $input_to;
            } elseif ($filter_type === 'weekly') {
                // This Week (Mon - Sun)
                $start_date = date('Y-m-d', strtotime('monday this week'));
                $end_date   = date('Y-m-d', strtotime('sunday this week'));
            } elseif ($filter_type === 'all') {
                $start_date = '2000-01-01';
                $end_date   = '2100-12-31';
            }
            // else 'monthly' (already set as default)

            // -------------------------------------------------------------------------
            // QUERIES
            // -------------------------------------------------------------------------

            // 1. Job Collection (Based on updated_at, as that's when money is collected/job closed)
            // Note: We check DATE(updated_at) against our range
            $c_sql = "SELECT SUM(total_collection) as total FROM jobs 
                      WHERE DATE(updated_at) BETWEEN '$start_date' AND '$end_date'
                      AND status != 'Cancelled'"; 
            $res_c = $conn->query($c_sql);
            $job_collection = ($res_c) ? ($res_c->fetch_assoc()['total'] ?? 0) : 0;

            // 2. AMC Income (Based on created_at - when the AMC was sold/entered)
            $amc_sql = "SELECT SUM(amount) as total FROM amc_records 
                        WHERE DATE(created_at) BETWEEN '$start_date' AND '$end_date'";
            $res_amc = $conn->query($amc_sql);
            $amc_collection = ($res_amc) ? ($res_amc->fetch_assoc()['total'] ?? 0) : 0;

            $total_collection = $job_collection + $amc_collection;

            // 3. Expenses (Based on created_at)
            $e_sql = "SELECT SUM(amount) as total FROM expenses 
                      WHERE DATE(created_at) BETWEEN '$start_date' AND '$end_date'";
            $res_e = $conn->query($e_sql);
            $expense = ($res_e) ? ($res_e->fetch_assoc()['total'] ?? 0) : 0;
            
            // 4. Pending Due (Total Bill - Collection) where Bill > Collection
            // Pending is usually a "current state" metric, not necessarily date-bound, 
            // BUT for a report, maybe we only want pending/dues from jobs in this period?
            // Usually "Pending Due" implies "Total Outstanding in the market". 
            // Let's keep it defined by the date range of the JOB to show "Receivables generated in this period".
            $p_sql = "SELECT SUM(total_bill - total_collection) as pending FROM jobs 
                      WHERE total_bill > total_collection 
                      AND status != 'Cancelled'
                      AND DATE(updated_at) BETWEEN '$start_date' AND '$end_date'";
            $res_p = $conn->query($p_sql);
            $pending = ($res_p) ? ($res_p->fetch_assoc()['pending'] ?? 0) : 0;

            // 5. Net Cash
            $profit = $total_collection - $expense;
        ?>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <!-- Collection Widget -->
            <div class="bg-white rounded-xl p-6 shadow-sm border-l-4 border-emerald-500 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Collection (This Month)</p>
                        <h3 class="text-2xl font-bold text-gray-800">₹<?= number_format($total_collection, 2) ?></h3>
                        <p class="text-[10px] text-gray-500 font-medium">Jobs: <?= number_format($job_collection) ?> + AMC: <?= number_format($amc_collection) ?></p>
                    </div>
                    <div class="p-2 bg-emerald-50 rounded-lg text-emerald-600">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    </div>
                </div>
            </div>

            <!-- Expense Widget -->
            <div class="bg-white rounded-xl p-6 shadow-sm border-l-4 border-red-500 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Expenses (This Month)</p>
                        <h3 class="text-2xl font-bold text-gray-800">₹<?= number_format($expense, 2) ?></h3>
                    </div>
                    <div class="p-2 bg-red-50 rounded-lg text-red-600">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 17h8m0 0V9m0 8l-8-8-4 4-6-6"/></svg>
                    </div>
                </div>
            </div>

            <!-- Profit Widget -->
            <div class="bg-white rounded-xl p-6 shadow-sm border-l-4 border-indigo-500 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Net Cash in Hand</p>
                        <h3 class="text-2xl font-bold text-gray-800">₹<?= number_format($profit, 2) ?></h3>
                    </div>
                    <div class="p-2 bg-indigo-50 rounded-lg text-indigo-600">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    </div>
                </div>
            </div>

            <!-- Pending Widget -->
            <div class="bg-white rounded-xl p-6 shadow-sm border-l-4 border-amber-500 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Pending Due</p>
                        <h3 class="text-2xl font-bold text-gray-800">₹<?= number_format($pending, 2) ?></h3>
                    </div>
                    <div class="p-2 bg-amber-50 rounded-lg text-amber-600">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                    </div>
                </div>
            </div>
        </div>

        <?php else: 
            // STANDARD DASHBOARD (Admin, Tech, Telecaller, etc.)
            
            // Filter logic for Technician/Staff
            $user_id = $_SESSION['user_id'];
            $is_restricted = !in_array($role, ['admin', 'telecaller', 'team_leader']);
            
            // Technician Wallet Logic
            $wallet_balance = 0;
            if ($is_restricted) {
                // Cash from Jobs (Not Deposited)
                $wj_q = $conn->query("SELECT SUM(total_bill) as t FROM jobs WHERE assigned_to = $user_id AND status='Completed' AND payment_mode IN ('Cash', 'UPI') AND is_deposited=0");
                $w_jobs = ($wj_q) ? ($wj_q->fetch_assoc()['t'] ?? 0) : 0;
                
                // You can add AMC wallet logic here later if Technicians sell AMC directly
                $wallet_balance = $w_jobs;
            }

            $filter = $_GET['filter'] ?? 'monthly'; 
            $from_date = $_GET['from_date'] ?? null;
            $to_date = $_GET['to_date'] ?? null;
            
            $whereClause = "";
            
            if ($from_date && $to_date) {
                // Custom Date Range
                $whereClause = " AND DATE(created_at) BETWEEN '$from_date' AND '$to_date'";
            } elseif ($filter == 'weekly') {
                $whereClause = " AND YEARWEEK(created_at, 1) = YEARWEEK(CURDATE(), 1)";
            } elseif ($filter == 'monthly') {
                $whereClause = " AND MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())";
            }
            
            $stats = ['New' => 0, 'On Going' => 0, 'Pending' => 0, 'Cancelled' => 0, 'Not Answered' => 0, 'Refused' => 0];
            $total_jobs = 0;

            if ($is_restricted) {
                // Technician sees only their stats
                $sql = "SELECT status, COUNT(*) as count FROM jobs WHERE assigned_to = $user_id $whereClause GROUP BY status";
                $total_query = "SELECT COUNT(*) as c FROM jobs WHERE assigned_to = $user_id $whereClause";
            } else {
                // Admin/Others see all
                // Note: WHERE 1=1 is not needed if we check empty, but good for appending
                $sql = "SELECT status, COUNT(*) as count FROM jobs WHERE 1=1 $whereClause GROUP BY status";
                $total_query = "SELECT COUNT(*) as c FROM jobs WHERE 1=1 $whereClause";
            }

            // Get Total Count
            $t_res = $conn->query($total_query);
            $total_jobs = ($t_res) ? $t_res->fetch_assoc()['c'] : 0;

            // Get Status Breakdown
            $result = $conn->query($sql);
            if ($result) { while ($row = $result->fetch_assoc()) { $stats[$row['status']] = $row['count']; } }
        ?>
        
        <?php if ($is_restricted): ?>
        <!-- Technician Wallet Widget -->
        <div class="mb-8">
            <div class="bg-gradient-to-r from-gray-900 to-gray-800 rounded-xl p-6 shadow-lg text-white flex justify-between items-center relative overflow-hidden">
                <!-- Background Pattern -->
                <div class="absolute top-0 right-0 -mr-8 -mt-8 w-32 h-32 rounded-full bg-white opacity-5"></div>
                
                <div class="relative z-10">
                    <p class="text-gray-400 text-xs font-bold uppercase tracking-widest mb-1">My Virtual Wallet</p>
                    <h2 class="text-4xl font-bold <?= $wallet_balance > 0 ? 'text-green-400' : 'text-gray-200' ?>">
                        ₹<?= number_format($wallet_balance, 2) ?>
                    </h2>
                    <p class="text-sm text-gray-400 mt-1 flex items-center gap-2">
                        <?php if($wallet_balance > 0): ?>
                            <span class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></span>
                            Cash/UPI in Hand (Not Deposited)
                        <?php else: ?>
                            All settled with Admin.
                        <?php endif; ?>
                    </p>
                </div>

                <div class="relative z-10 text-right">
                    <a href="wallet_history.php" class="inline-flex items-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-bold px-4 py-2 rounded-lg transition-colors shadow-md">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                        View History
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <!-- Total Jobs Widget -->
            <div class="bg-white rounded-xl p-6 shadow-sm border-l-4 border-indigo-600 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Total Jobs</p>
                        <h3 class="text-3xl font-bold text-gray-800"><?= $total_jobs ?></h3>
                    </div>
                    <div class="p-2 bg-indigo-50 rounded-lg text-indigo-600">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/></svg>
                    </div>
                </div>
            </div>

            <?php 
            // Total Active AMC Count (Admin View)
            // Assuming 'active' means current date is within start_date and end_date (1 year later usually)
            // Or just raw count of records if we don't have expiration logic yet.
            // Let's count ALL for now or check expiry. 
            // Based on previous code, we just insert. Let's Count Total Records in amc_records.
            $amc_count_sql = "SELECT COUNT(*) as c FROM amc_records"; 
            /* If we want to filter by date (Active Only):
               $amc_count_sql = "SELECT COUNT(*) as c FROM amc_records WHERE start_date <= CURDATE() AND DATE_ADD(start_date, INTERVAL 1 YEAR) >= CURDATE()";
               Let's stick to simple total for now unless requested active only. Request said "Total Count of AMC records".
            */
            if ($is_restricted) {
                // If technician, maybe don't show AMC count or show 0? 
                // Or if we want tech to see total amcs:
                $amc_total = $conn->query($amc_count_sql)->fetch_assoc()['c'];
            } else {
                $amc_total = $conn->query($amc_count_sql)->fetch_assoc()['c'];
            }
            
            // USER FEEDBACK CORRECTION: User expects "Active AMC" to reflect the AMC Jobs visible in "Recent Tickets"
            // So we should count JOBS where has_amc = 1.
            $amc_jobs_count_sql = "SELECT COUNT(*) as c FROM jobs WHERE has_amc = 1 $whereClause"; 
            $amc_jobs_total = $conn->query($amc_jobs_count_sql)->fetch_assoc()['c'];
            ?>
            <!-- Total AMC Widget -->
            <div class="bg-white rounded-xl p-6 shadow-sm border-l-4 border-yellow-500 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">AMC Jobs</p>
                        <h3 class="text-3xl font-bold text-gray-800"><?= $amc_jobs_total ?></h3>
                        <p class="text-[10px] text-gray-400 mt-1">Contracts Sold: <?= $amc_total ?></p>
                    </div>
                    <div class="p-2 bg-yellow-50 rounded-lg text-yellow-600">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                    </div>
                </div>
            </div>

            <?php
            $colors = [
                'New' => 'blue', 'On Going' => 'amber', 'Pending' => 'purple',
                'Cancelled' => 'red', 'Not Answered' => 'emerald', 'Refused' => 'gray'
            ];
            foreach ($stats as $status => $count):
                $color = $colors[$status] ?? 'gray';
            ?>
            <div class="bg-white rounded-xl p-6 shadow-sm border-l-4 border-<?= $color ?>-500 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1"><?= $status ?></p>
                        <h3 class="text-3xl font-bold text-gray-800"><?= $count ?></h3>
                    </div>
                    <div class="p-2 bg-<?= $color ?>-50 rounded-lg text-<?= $color ?>-600">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Recent Tickets (Common for All) -->
        <div class="bg-white rounded-xl shadow-sm overflow-hidden">
            <div class="p-6 border-b border-gray-100 flex justify-between items-center">
                <h3 class="font-bold text-gray-800">Recent Tickets</h3>
                <a href="all_jobs.php" class="text-indigo-600 hover:text-indigo-800 text-sm font-medium">View All</a>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full whitespace-nowrap">
                    <thead class="bg-gray-50">
                        <tr class="text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <th class="px-6 py-4">ID</th>
                            <th class="px-6 py-4">Customer</th>
                            <th class="px-6 py-4">Device</th>
                            <th class="px-6 py-4">Status</th>
                            <th class="px-6 py-4">Date</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 bg-white">
                        <?php
                        // Logic defined above for standard dashboard, but redundant check for accounts if needed
                         $is_restricted_recent = !in_array($role, ['admin', 'telecaller', 'team_leader', 'accounts']);
                         $user_id = $_SESSION['user_id'];
                         
                         // Apply the same date filter ($whereClause) to the recent tickets list if it exists
                         // $whereClause is defined above for Standard Dashboard. 
                         // For Accounts, we might need to redefine or ensure scope. 
                         // But Accounts has its own block above. This block is "Recent Tickets (Common for All)".
                         // If we are Accounts, $whereClause might not be defined or different.
                         // Let's ensure $whereClause is valid. If null, make empty.
                         $whereClause = $whereClause ?? "";

                         if ($is_restricted_recent) {
                            $recent = $conn->query("SELECT id, customer_name, customer_phone, address, device_model, status, service_type, has_amc, created_at FROM jobs WHERE assigned_to = $user_id $whereClause ORDER BY created_at DESC LIMIT 5");
                         } else {
                            // Use 1=1 to safely append whereClause (which starts with AND)
                            $recent = $conn->query("SELECT id, customer_name, customer_phone, address, device_model, status, service_type, has_amc, created_at FROM jobs WHERE 1=1 $whereClause ORDER BY created_at DESC LIMIT 5");
                         }

                        if ($recent && $recent->num_rows > 0):
                            while($row = $recent->fetch_assoc()):
                                $color = 'gray'; // Default
                                if(isset($colors) && isset($colors[$row['status']])) {
                                    $color = $colors[$row['status']];
                                } else {
                                    // Fallback colors if $colors isn't defined (e.g. in accounts view)
                                     $c_map = ['New' => 'blue', 'On Going' => 'amber', 'Pending' => 'purple', 'Cancelled' => 'red', 'Not Answered' => 'emerald', 'Refused' => 'gray'];
                                     $color = $c_map[$row['status']] ?? 'gray';
                                }
                                $is_amc = !empty($row['has_amc']);
                        ?>
                        <tr class="hover:bg-gray-50 transition-colors cursor-pointer <?= $is_amc ? 'bg-yellow-50 hover:bg-yellow-100' : '' ?>" onclick="window.location.href='edit_job.php?id=<?= $row['id'] ?>'">
                            <td class="px-6 py-4 text-sm font-bold text-gray-900">
                                CTSC<?= $row['id'] ?>
                                <?php if($is_amc): ?>
                                    <span class="block text-[10px] text-yellow-600 font-extrabold flex items-center gap-1 mt-1">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 2a1 1 0 011 1v1.323l3.954 1.582 1.699-3.181A1 1 0 0118 2.22l.205.293a1 1 0 01-.2 1.252l-2.03 2.029 3.125 3.906a1 1 0 01-.175 1.48l-1.035 1.035a1 1 0 01-1.414 0l-1.92-1.92-4.29 4.29-1.92 1.92a1 1 0 01-1.414 0l-1.035-1.035a1 1 0 010-1.414l5.225-5.225-2.03-2.03a1 1 0 011.252-.2l.293.205a1 1 0 01.528 1.303L11.323 11H13a1 1 0 011-1H4a1 1 0 010-2h6.323l-3.582-3.954A1 1 0 018 3.22V3a1 1 0 011-1z" clip-rule="evenodd" /><path d="M5 11h2a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v2a2 2 0 002 2z" /></svg>
                                        AMC
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-600">
                                <div class="font-medium text-gray-900"><?= htmlspecialchars($row['customer_name']) ?></div>
                                <div class="text-xs text-gray-500 mt-0.5"><?= htmlspecialchars($row['customer_phone']) ?></div>
                                <?php if(!empty($row['address'])): ?>
                                    <div class="text-xs text-gray-400 mt-1 max-w-[150px] truncate" title="<?= htmlspecialchars($row['address']) ?>">
                                        📍 <?= htmlspecialchars($row['address']) ?>
                                    </div>
                                <?php endif; ?>
                                <?php if($is_amc): ?>
                                    <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-yellow-100 text-yellow-800 mt-1">
                                        Special
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-500"><?= htmlspecialchars($row['device_model']) ?></td>
                            <td class="px-6 py-4">
                                <span class="px-3 py-1 text-xs font-semibold rounded-full bg-<?= $color ?>-100 text-<?= $color ?>-800">
                                    <?= $row['status'] ?>
                                </span>
                                <?php if(isset($row['service_type']) && $row['service_type'] == 'Recall'): ?>
                                    <span class="ml-2 px-2 py-0.5 text-[10px] uppercase font-bold text-white bg-red-500 rounded shadow-sm">Recall</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-400"><?= date('M d', strtotime($row['created_at'])) ?></td>
                        </tr>
                        <?php endwhile; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <div class="block md:hidden mt-6">
             <a href="create_job.php" class="chat w-full bg-indigo-600 text-white py-3 rounded-lg flex items-center justify-center gap-2 font-bold shadow-lg">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                Create New Ticket
            </a>
        </div>
    </main>
    
</body>
</html>
