<!DOCTYPE html>
<html lang="en">
<head>
    <title>Teledata Print</title>
    <meta charset="utf-8">
    <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: 10px !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='teledata.php';" class="btn btn-secondary">Back</button>
    </div>

    <div class="print-title" >Teledata Report</div>

    <?php
    include 'branch_connection.php';
    
    ini_set('display_errors', 0);
    error_reporting(E_ALL);

    $start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
    $end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';
    $segment_filter = (isset($_GET['segment']) && $_GET['segment'] !== '') ? (int)$_GET['segment'] : null;
    $company_name = (isset($_GET['company_name']) && $_GET['company_name'] !== '') ? $_GET['company_name'] : null;

    $date_range_display = "";
    if ($start_date || $end_date) {
        $date_range_display = ($start_date ? $start_date : 'Start Date') . 
                              " to " . 
                              ($end_date ? $end_date : 'End Date');
    } else {
        $date_range_display = "All Records (No date filter applied)";
    }

// Function to get real IP address
function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        // IP from shared internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // IP passed from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        // In case of multiple IPs, take the first one
        $ip = explode(',', $ip)[0];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

$user_ip = getUserIP();


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: Telecalling Database as of " . htmlspecialchars($date_range_display) . "</b></span>
        <span style='font-weight:bold;font-size:12px;'> IP Address: " . htmlspecialchars($user_ip) . " | User: " . htmlspecialchars($_SESSION['username']) . "</span>
      </div>";



    $teledata_rows = [];
    $sql = "SELECT t.*, s.segment_name, u.name 
            FROM teledata t 
            LEFT JOIN segments s ON t.segment = s.id 
            LEFT JOIN users u ON t.staff = u.id 
            WHERE 1=1";

    $params = [];
    $types = "";

    if (!is_null($company_name)) {
        $sql .= " AND t.company_name LIKE ?";
        $params[] = '%' . $company_name . '%';
        $types .= "s";
    }

    if (!is_null($segment_filter)) {
        $sql .= " AND t.segment = ?";
        $params[] = $segment_filter;
        $types .= "i";
    }

    if (!empty($start_date)) {
        $sql .= " AND t.created_at >= ?";
        $params[] = $start_date;
        $types .= "s";
    }

    if (!empty($end_date)) {
        $sql .= " AND t.created_at <= ?";
        $params[] = $end_date;
        $types .= "s";
    }

    $sql .= " ORDER BY t.id DESC";

    $stmt = $conn->prepare($sql);
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }

    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $teledata_rows[] = $row;
        }
    }
    $stmt->close();
    
    ?>

    <table>
        <thead>
            <tr>
                <th style="width:10px;">#</th>
                <th style="width: 55px;">Date</th>
                <th style="width: 250px;">Company</th>
                <th style="width: 100px;">Segment</th>
                <th style="width: 75px;">Mobile No.</th>
                <th style="width: 55px;">Location</th>
                <th style="width:10px;">BDO</th>
                <th style="width:60px;">Status</th>
                <th style="width: 140px;">Remarks</th>
            </tr>
        </thead>
        <tbody>
            <?php if (count($teledata_rows) > 0): ?>
            <?php $sl = 1; // initialize serial number ?>
                <?php foreach ($teledata_rows as $row): ?>
                    <tr>
                        <td><?= $sl++ ?></td>
                        <td><?= date('Y-m-d', strtotime($row['created_at'])) ?></td>
                        <td><?= htmlspecialchars($row['company_name']) ?></td>
                        <td><?= htmlspecialchars($row['segment_name']) ?></td>
                        <td><?= htmlspecialchars($row['mobile']) ?></td>
                        <td><?= htmlspecialchars($row['location']) ?></td>
                        <td><?= htmlspecialchars($row['name']) ?></td>
                        <td><?= htmlspecialchars($row['status']) ?></td>
                        <td></td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="7" class="text-center">No records found.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>

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

    <!-- ✅ jsPDF CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

    <!-- ✅ DOWNLOAD PDF SCRIPT -->
    <script>
    async function downloadPDF() {
        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF("p", "pt", "a4");

        await pdf.html(document.body, {
            callback: function (pdf) {
                pdf.save("Teledata_Report.pdf");
            },
            x: 10,
            y: 10,
            width: 580
        });
    }
    </script>

</body>
</html>
