<?php
session_start();
error_reporting(0);
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
if (!isset($_SESSION['userid'])) {
    header("Location: ../index.php");
    exit();
}

include 'branch_connection.php';

// Get filters from GET (from leads.php print button)
$filter_from_date = isset($_GET['from_date']) ? $_GET['from_date'] : '';
$filter_to_date = isset($_GET['to_date']) ? $_GET['to_date'] : '';
$filter_status = isset($_GET['filter_status']) ? $_GET['filter_status'] : '';

// Build SQL query with filters
$lead_sql = "SELECT * FROM tb_leads";
$filter_conditions = [];
$params = [];
$types = "";

if (!empty($filter_from_date) && !empty($filter_to_date)) {
    $filter_conditions[] = "followup_date BETWEEN ? AND ?";
    $types .= "ss";
    $params[] = $filter_from_date;
    $params[] = $filter_to_date;
}

if (!empty($filter_status)) {
    $filter_conditions[] = "status = ?";
    $types .= "s";
    $params[] = $filter_status;
}

if (count($filter_conditions) > 0) {
    $lead_sql .= " WHERE " . implode(" AND ", $filter_conditions);
}

$lead_sql .= " ORDER BY id DESC";

// Prepare and execute
$stmt = $conn->prepare($lead_sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Print Leads</title>
<link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f9f9f9;
        }
        h1, h2 {
            text-align: center;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 5px 0;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 0px 0px 0px 10px;
            text-align: left;
            font-size: 13px;
            text-transform: capitalize;
        }
        th {
            background-color: #c1dfc3;
            color: black;
            font-weight: 600!important;
        }
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #ddd;
        }
        .no-print {
            text-align: right;
            margin-bottom: 20px;
        }
        .btn {
            padding: 10px 15px;
            margin-left: 5px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-info {
            background-color: #007BFF;
            color: white;
        }
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        .btn:hover {
            opacity: 0.8;
        }
        .no-print {
                display:flex;
            }
            /* FORCE BACKGROUND COLORS & GRAPHICS IN PRINT */
* {
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
}
        @media print {
            @page {
    margin: 0;
    size: A4 landscape; /* FORCE A4, PORTRAIT */
}
            .no-print {
                display: none;
            }
            table {
                border: none;
            }
            th, td {
                border: 1px dashed black;
                padding: 2px;
                font-size:10px;
            }
            body {
                margin: 0 !important;
                padding: 5px !important;
            }
        }
        .print-title {
            display: none;
            margin-bottom: 20px;
            font-size: 18px;
            font-weight: bold;
        }
        .date-range-display {
            margin-bottom: 20px;
            font-style: italic;
            color: #555;
        }
    </style>
</head>
<body>
    <!-- ✅ TOP BUTTONS -->
    <div class="no-print" style="width:100%;justify-content:center;">
        <button onclick="window.print();" class="btn btn-info">Print</button>
        <!-- <button onclick="downloadPDF()" class="btn btn-secondary">Download PDF</button> -->
        <button onclick="window.location.href='leads.php';" class="btn btn-secondary">Back</button>
    </div>
<!--<h1 style="margin-bottom:0!important;margin-top:2px!important;font-size:25px;">Leads List</h1>-->
<p style="width:100%;display:flex;justify-content:space-between;margin:0 0 0 0;font-size:10px;">
<span>
<?php 
    if($filter_from_date && $filter_to_date) {
        echo "From: ".htmlspecialchars($filter_from_date)." To: ".htmlspecialchars($filter_to_date);
    } 
?>
</span>
<span>
<?php
    // Get user IP
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $user_ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $user_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $user_ip = $_SERVER['REMOTE_ADDR'];
    }

    // Get username from session
    $username = isset($_SESSION['username']) ? $_SESSION['username'] : 'Admin';

    echo "<div class='date-range-display' style='display:flex;width:100%;justify-content:space-between;margin-bottom:5px;font-size:10px;'>
        <span><b style='font-size:12px;'>Salesmaster: Leads Database as of 10/11/25 to 15/11/25</b></span>
        <span style='font-weight:bold;font-size:12px;'> IP Address: " . htmlspecialchars($user_ip) . " | User: " . htmlspecialchars($_SESSION['username']) . "</span>
      </div>";
?>
</span>

<?php if($filter_status) echo " | Status: ".htmlspecialchars($filter_status); ?>
</p>


<table id="leadsTable" class="table table-bordered">
    <thead>
        <tr>
            <th>#</th>
            <th>Mobile</th>
            <th style="width:10px;">Cus.Name</th>
            <th>Company Name</th>
            <th>Segment</th>
            <th>Location</th>
            <th>Remarks</th>
            <th>Status</th>
            <th>Category</th>
            <th>Follow Up Date</th>
        </tr>
    </thead>
    <tbody>
        <?php if ($result && $result->num_rows > 0):
            $count = 1;
            while ($lead = $result->fetch_assoc()): 
            $segment_id = $lead['segment'];
            // Get segment name
            $seg_query = mysqli_query($conn, "SELECT segment_name FROM segments WHERE id='$segment_id'");
            $seg = mysqli_fetch_assoc($seg_query);
            $segment_name = $seg['segment_name'] ?? 'N/A';?>
                <tr>
                    <td><?php echo $count++; ?></td>
                    <td><?php echo htmlspecialchars($lead['mobile']); ?></td>
                    <td><?php echo htmlspecialchars($lead['customer_name']); ?></td>
                    <td><?php echo htmlspecialchars($lead['company_name']); ?></td>
                    <td><?php echo htmlspecialchars($segment_name); ?></td>
                    <td><?php echo htmlspecialchars($lead['location']); ?></td>
                    <td><?php echo htmlspecialchars($lead['remarks']); ?></td>
                    <td><?php echo htmlspecialchars($lead['status']); ?></td>
                    <td><?php echo htmlspecialchars($lead['category']); ?></td>
                    <td><?php echo htmlspecialchars($lead['followup_date']); ?></td>
                </tr>
        <?php endwhile; else: ?>
            <tr><td colspan="10" class="text-center">No records found.</td></tr>
        <?php endif; ?>
    </tbody>
</table>

<script>
document.getElementById('downloadPDF').addEventListener('click', function () {
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF('l', 'pt', 'a4'); // landscape
    doc.setFontSize(10);
    doc.text("Leads List", 40, 40);

    // Grab table
    const table = document.getElementById('leadsTable');
    const rows = [];
    for (let i = 0; i < table.rows.length; i++) {
        const cols = table.rows[i].cells;
        const row = [];
        for (let j = 0; j < cols.length; j++) {
            row.push(cols[j].innerText);
        }
        rows.push(row);
    }

    // Use autoTable plugin if available, else simple approach
    if (doc.autoTable) {
        doc.autoTable({ head: [rows[0]], body: rows.slice(1), startY: 50 });
    } else {
        // Basic table
        let y = 50;
        rows.forEach((r) => {
            let x = 40;
            r.forEach((c) => {
                doc.text(c.toString(), x, y);
                x += 80;
            });
            y += 20;
        });
    }

    doc.save('leads.pdf');
});
</script>

</body>
</html>

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