<?php
session_start();
include '../config.php';

ini_set('display_errors', 0);
error_reporting(E_ALL);
$username = isset($_SESSION['username']) ? $_SESSION['username'] : '';
$userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 'Not set';
if (!isset($_SESSION['userid'])) {
    header("Location: ../index.php");
    exit();
}
$message = "";
$edit_mode = false;
$edit_id = 0;
$preview_data = []; // For CSV preview

// Handle import from CSV using fgetcsv
if (isset($_POST['import'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == UPLOAD_ERR_OK) {
        $file = $_FILES['csv_file']['tmp_name'];

        // Process CSV import
        $import_count = 0;
        $skip_count = 0;
        $error_rows = [];

        if (($handle = fopen($file, 'r')) !== false) {
            $rowIndex = 0;
            while (($data = fgetcsv($handle, 1000, ",")) !== false) {
                if ($rowIndex++ < 5) { // Preview first 5 rows
                    $preview_data[] = $data;
                }
            }
            fclose($handle);
        }

        // Now process the import
        if (($handle = fopen($file, 'r')) !== false) {
            $rowIndex = 0;
            while (($data = fgetcsv($handle, 1000, ",")) !== false) {
                $rowIndex++;
                if ($rowIndex == 1) continue; // Skip header row

                if (count($data) < 5) {
                    $skip_count++;
                    continue;
                }

                $company_name = strtoupper(trim($data[0]));
                $mobile = preg_replace('/\D/', '', trim($data[1]));
                $location = strtoupper(trim($data[2]));
                $segment = intval(trim($data[3]));
                $staff = trim($data[4]);
                $status = trim($data[5]);

                if (empty($company_name) || empty($mobile) || empty($location) || empty($segment) || empty($status)) {
                    $skip_count++;
                    continue;
                }

                $stmt = $conn->prepare("SELECT id FROM teledata WHERE mobile = ?");
                $stmt->bind_param("s", $mobile);
                $stmt->execute();
                $stmt->store_result();

                if ($stmt->num_rows > 0) {
                    $skip_count++;
                    $stmt->close();
                    continue;
                }
                $stmt->close();

                $stmt = $conn->prepare("INSERT INTO teledata (company_name, mobile, location, segment, staff, status, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
                $stmt->bind_param("ssssis", $company_name, $mobile, $location, $segment, $staff, $status);

                if ($stmt->execute()) {
                    $tele_id = $stmt->insert_id;

                    if ($status === 'Interested') {
                        $stmt2 = $conn->prepare("INSERT INTO tb_positiveleads (tel_id, mobile, company_name, segment, location, status, staff, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
                    } elseif ($status === 'Not Interested') {
                        $stmt2 = $conn->prepare("INSERT INTO tb_leads (tel_id, mobile, company_name, segment, location, status, staff, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
                    } else {
                        $stmt2 = null;
                    }

                    if ($stmt2) {
                        $stmt2->bind_param("issssss", $tele_id, $mobile, $company_name, $segment, $location, $status, $staff);
                        $stmt2->execute();
                        if ($stmt2->error) {
                            $error_rows[] = $rowIndex . " (lead insert error: " . $stmt2->error . ")";
                        }
                        $stmt2->close();
                    }
                    $import_count++;
                } else {
                    $error_rows[] = $rowIndex . " (teledata insert error: " . $stmt->error . ")";
                }
                $stmt->close();
            }
            fclose($handle);
            $message = "Import complete. Successfully imported: $import_count. Skipped rows: $skip_count.";
            if (!empty($error_rows)) {
                $message .= " Errors on rows: " . implode(", ", $error_rows) . ".";
            }
        } else {
            $message = "Error opening uploaded CSV file.";
        }
    } else {
        $message = "Error uploading file.";
    }
}

// Delete record
if (isset($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);

    $stmt = $conn->prepare("DELETE FROM teledata WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        $message = "Record deleted successfully.";
        $conn->query("DELETE FROM tb_leads WHERE tel_id = $delete_id");
        $conn->query("DELETE FROM tb_positiveleads WHERE tel_id = $delete_id");
    } else {
        $message = "Error deleting record: " . $stmt->error;
    }
    $stmt->close();
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && !isset($_POST['import'])) {
    $company_name = strtoupper(trim($_POST['company_name']));
    $mobile = trim($_POST['mobile']);
    $location = strtoupper(trim($_POST['location']));
    $segment = $_POST['segment'];
    $status = $_POST['status'];
    $remarks = $_POST['remarks'];
    $staff = $_POST['staffid'];
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;

    $stmt = $conn->prepare("SELECT id FROM teledata WHERE mobile = ? AND id != ?");
    $stmt->bind_param("si", $mobile, $id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $message = "Error: Mobile number already exists.";
        $stmt->close();
    } else {
        $stmt->close();
        if ($id > 0) {
            $stmt = $conn->prepare("UPDATE teledata SET company_name=?, remarks=?, mobile=?, location=?, segment=?, staff=?, status=? WHERE id = ?");
            $stmt->bind_param("ssssissi", $company_name, $remarks, $mobile, $location, $segment, $staff, $status, $id);
            if ($stmt->execute()) {
                $message = "Record updated successfully.";

                if ($status === 'Interested') {
                    $stmt2 = $conn->prepare("INSERT INTO tb_positiveleads (remarks,tel_id, mobile, company_name, segment, location, status, staff, created_at) VALUES (?,?, ?, ?, ?, ?, ?, ?, NOW())");
                    $stmt2->bind_param("sissssss", $remarks,$id, $mobile, $company_name, $segment, $location, $status, $staff);
                    $stmt2->execute();
                    $stmt2->close();
                    $conn->query("DELETE FROM teledata WHERE id = $id");
                } elseif ($status === 'Not Interested') {
                    $stmt2 = $conn->prepare("INSERT INTO tb_leads (remarks,tel_id, mobile, company_name, segment, location, status, staff, created_at) VALUES (?, ?,?, ?, ?, ?, ?, ?, NOW())");
                    $stmt2->bind_param("sissssss", $remarks,$id, $mobile, $company_name, $segment, $location, $status, $staff);
                    $stmt2->execute();
                    $stmt2->close();
                    $conn->query("DELETE FROM teledata WHERE id = $id");
                }
            } else {
                $message = "Error updating record: " . $stmt->error;
            }
            $stmt->close();
        } else {
            $status = 'No Action';
            $stmt = $conn->prepare("INSERT INTO teledata (company_name, mobile, location, segment, staff, status, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
            $stmt->bind_param("ssssis", $company_name, $mobile, $location, $segment, $staff, $status);
            if ($stmt->execute()) {
                $tele_id = $stmt->insert_id;
                $message = "New record created successfully.";

                if ($status === 'Interested') {
                    $stmt2 = $conn->prepare("INSERT INTO tb_positiveleads (tel_id, mobile, company_name, segment, location, status, staff, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
                    $stmt2->bind_param("issssss", $tele_id, $mobile, $company_name, $segment, $location, $status, $staff);
                    $stmt2->execute();
                    $stmt2->close();
                } elseif ($status === 'Not Interested') {
                    $stmt2 = $conn->prepare("INSERT INTO tb_leads (tel_id, mobile, company_name, segment, location, status, staff, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
                    $stmt2->bind_param("issssss", $tele_id, $mobile, $company_name, $segment, $location, $status, $staff);
                    $stmt2->execute();
                    $stmt2->close();
                }
            } else {
                $message = "Error inserting record: " . $stmt->error;
            }
            $stmt->close();
        }
    }
}

if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM teledata WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows == 1) {
        $edit_mode = true;
        $edit_row = $result->fetch_assoc();
    }
    $stmt->close();
}

$segments = [];
$sql = "SELECT id, segment_name FROM segments ORDER BY segment_name ASC";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $segments[] = $row;
    }
}

$limit = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0 ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $limit;
$segment_filter = isset($_GET['segment']) && $_GET['segment'] !== '' ? (int)$_GET['segment'] : null;

// Date filter
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : null;
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : null;

$teledata_rows = [];

if ($username === 'admin') {
    $sql2 = "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 (? IS NULL OR t.segment = ?) 
             AND (? IS NULL OR t.created_at >= ?) 
             AND (? IS NULL OR t.created_at <= ?) 
             ORDER BY t.id DESC LIMIT ? OFFSET ?";
    $stmt2 = $conn->prepare($sql2);
    $stmt2->bind_param("iiissssi", $segment_filter, $segment_filter, $start_date, $start_date, $end_date, $end_date, $limit, $offset);
} else {
    $sql2 = "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 t.staff = ? 
             AND (? IS NULL OR t.segment = ?) 
             AND (? IS NULL OR t.created_at >= ?) 
             AND (? IS NULL OR t.created_at <= ?) 
             ORDER BY t.id DESC LIMIT ? OFFSET ?";
    $stmt2 = $conn->prepare($sql2);
    $stmt2->bind_param("iiissssi", $userid, $segment_filter, $segment_filter, $start_date, $start_date, $end_date, $end_date, $limit, $offset);
}

$stmt2->execute();
$result2 = $stmt2->get_result();
if ($result2 && $result2->num_rows > 0) {
    while ($row2 = $result2->fetch_assoc()) {
        $teledata_rows[] = $row2;
    }
}
$stmt2->close();

if ($username === 'admin') {
    $total_sql = "SELECT COUNT(*) as total FROM teledata WHERE (? IS NULL OR segment = ?) 
                  AND (? IS NULL OR created_at >= ?) 
                  AND (? IS NULL OR created_at <= ?)";
    $total_stmt = $conn->prepare($total_sql);
    $total_stmt->bind_param("iiisss", $segment_filter, $segment_filter, $start_date, $start_date, $end_date, $end_date);
} else {
    $total_sql = "SELECT COUNT(*) as total FROM teledata WHERE staff = ? 
                  AND (? IS NULL OR segment = ?) 
                  AND (? IS NULL OR created_at >= ?) 
                  AND (? IS NULL OR created_at <= ?)";
    $total_stmt = $conn->prepare($total_sql);
    $total_stmt->bind_param("iiisss", $userid, $segment_filter, $segment_filter, $start_date, $start_date, $end_date, $end_date);
}

$total_stmt->execute();
$total_result = $total_stmt->get_result();
$total_row = $total_result->fetch_assoc();
$total_records = $total_row['total'];
$total_stmt->close();

$total_pages = ceil($total_records / $limit);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Leads Programers International</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="author" content="DexignLab">
    <meta name="robots" content="index, follow">
    <meta name="format-detection" content="telephone=no">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" type="image/png" href="assets/images/favicon.png">
    <link href="assets/vendor/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-datepicker-master/css/bootstrap-datepicker.min.css" rel="stylesheet">
    <link href="assets/vendor/owl-carousel/owl.carousel.css" rel="stylesheet">
    <link href="assets/css/jquery.localizationTool.css" rel="stylesheet">
    <link class="main-css" href="assets/css/style.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">

    <style>
        @media print {
            .no-print {
                display: none; /* Hide elements with the class 'no-print' */
            }
        }
    </style>
</head>
<body>
    <div id="preloader">
        <div class="lds-ripple"><div></div><div></div></div>
    </div>
    <div id="main-wrapper">
        <div class="nav-header">
            <a href="index.html" class="brand-logo"><img src="assets/images/logo-02.svg" alt=""></a>
            <div class="nav-control">
                <div class="hamburger"><span class="line"></span><span class="line"></span><span class="line"></span></div>
            </div>
        </div>
        <div class="header">
            <div class="header-content">
                <nav class="navbar navbar-expand">
                    <div class="collapse navbar-collapse justify-content-between">
                        <div class="header-left">
                            <div class="dashboard_bar">Teledata</div>
                        </div>
                        <ul class="navbar-nav header-right">
                            <li class="nav-item dropdown notification_dropdown">
                                <a class="nav-link bell dlab-theme-mode p-0" href="javascript:void(0);">
                                    <i id="icon-light" class="fas fa-sun"></i>
                                    <i id="icon-dark" class="fas fa-moon"></i>
                                </a>
                            </li>
                            <?php
                                $title = "Php Header Footer";
                                include "logout.php";
                            ?>
                        </ul>
                    </div>
                </nav>
            </div>
        </div>
        <?php
            $title = "Php Header Footer";
            include "header.php";
        ?>
        <div class="content-body">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-body" style="padding: 18px;">
                                <div class="basic-form">
                                    <?php if (!empty($message)): ?>
                                        <div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
                                    <?php endif; ?>
                                    <form method="POST" action="" enctype="multipart/form-data">
                                        <input type="hidden" name="id" value="<?= $edit_mode ? htmlspecialchars($edit_row['id']) : '' ?>">
                                        <input type="hidden" name="staffid" value="<?= $edit_mode ? htmlspecialchars($edit_row['staff']) : '' ?>">
                                        <div class="row">
                                            <div class="mb-2 col-md-12">
                                                <input type="text" name="company_name" class="form-control" placeholder="Company" required value="<?= $edit_mode ? htmlspecialchars($edit_row['company_name']) : '' ?>">
                                            </div>
                                            <div class="mb-2 col-md-12">
                                                <input type="number" name="mobile" class="form-control" placeholder="Mobile No." required value="<?= $edit_mode ? htmlspecialchars($edit_row['mobile']) : '' ?>">
                                            </div>
                                            <div class="mb-2 col-md-12">
                                                <input type="text" name="location" class="form-control" placeholder="Location" required value="<?= $edit_mode ? htmlspecialchars($edit_row['location']) : '' ?>">
                                            </div>
                                            <div class="mb-2 col-md-12">
                                                <select id="inputState" name="segment" class="default-select form-control wide" required>
                                                    <option value="" disabled <?= $edit_mode ? '' : 'selected' ?>>Segment</option>
                                                    <?php foreach ($segments as $seg): ?>
                                                        <option value="<?= htmlspecialchars($seg['id']) ?>" <?= $edit_mode && $edit_row['segment'] == $seg['id'] ? 'selected' : '' ?>>
                                                            <?= htmlspecialchars($seg['segment_name']) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="mb-2 col-md-12">
                                                <select id="inputStatus" <?= $edit_mode ? '' : 'readonly' ?> class="default-select form-control wide" name="status" required>
                                                    <option value="" disabled <?= $edit_mode ? '' : 'selected' ?>>Select Status</option>
                                                    <?php
                                                    $statuses = ['No Action', 'Interested', 'Not Interested'];
                                                    $current_status = $edit_mode ? (isset($edit_row['status']) ? $edit_row['status'] : '') : '';
                                                    foreach ($statuses as $s) {
                                                        $selected = ($current_status == $s) ? 'selected' : '';
                                                        echo "<option value=\"$s\" $selected>$s</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                            <div class="mb-2 col-md-12">
                                                <textarea name="remarks" class="form-control" placeholder="Remarks" required rows="3" <?= $edit_mode ? '' : 'readonly' ?>><?= $edit_mode ? htmlspecialchars($edit_row['remarks']) : '' ?></textarea>
                                            </div>
                                        </div>
                                        <button type="submit" class="btn btn-primary w-100"><?= $edit_mode ? 'Update' : 'Submit' ?></button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-xl-8">
                        <div class="row w-100 mb-2  ">
                            <div class="col-md-4 d-flex">
                                <form method="POST" action="" enctype="multipart/form-data" class="d-flex me-2">
                                    <input type="file" name="csv_file" class="form-control me-2" required>
                                    <button type="submit" name="import" class="btn btn-success">Import</button>
                                </form>
                            </div>
                            <div class="col-md-2">
                                <form method="GET" action="">
                                    <select name="segment" class="default-select form-control wide" onchange="this.form.submit()">
                                        <option value="">All Segments</option>
                                        <?php foreach ($segments as $seg): ?>
                                            <option value="<?= htmlspecialchars($seg['id']) ?>" <?= (isset($_GET['segment']) && $_GET['segment'] == $seg['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($seg['segment_name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </form>
                            </div>
                            <div class="col-md-3">
                                <form method="GET" action="" class="d-flex">
                                    <input type="date" name="start_date" class="form-control me-1" placeholder="Start Date" value="<?= isset($_GET['start_date']) ? htmlspecialchars($_GET['start_date']) : '' ?>">
                                    <input type="date" name="end_date" class="form-control me-1" placeholder="End Date" value="<?= isset($_GET['end_date']) ? htmlspecialchars($_GET['end_date']) : '' ?>">
                                    <button type="submit" class="btn btn-primary">Search</button>
                                </form>
                            </div>
                                <div class="col-md-2 d-flex align-items-start justify-content-end">
        <button onclick="window.print();" class="btn btn-info no-print">Print</button>
    </div>
                        </div>

                      

                        <div class="row">
                            <div class="table-responsive">
                                <table class="table table-hover table-responsive-sm table-small">
                                    <thead>
                                        <tr>
                                            <th class="td-padding-no">R#</th>
                                            <th class="td-padding-no">Company</th>
                                            <th class="td-padding-no">Mobile No.</th>
                                            <th class="td-padding-no">Location</th>
                                            <th class="td-padding-no">Segment</th>
                                            <th class="td-padding-no">Staff</th>
                                            <th class="td-padding-no">Status</th>
                                            <th class="td-padding-no" style="text-align: left!important;">Action</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (count($teledata_rows) > 0): ?>
                                            <?php $counter = $total_records - $offset; // Start from total records and decrement ?>
                                            <?php foreach ($teledata_rows as $row): ?>
                                                <tr>
                                                    <th class="td-padding-no"><?= $counter-- ?></th> <!-- Decrement the counter -->
                                                    <td class="td-padding-no"><?= htmlspecialchars($row['company_name']) ?></td>
                                                    <td class="td-padding-no"><?= htmlspecialchars($row['mobile']) ?></td>
                                                    <td class="td-padding-no"><?= htmlspecialchars($row['location']) ?></td>
                                                    <td class="td-padding-no"><?= htmlspecialchars($row['segment_name']) ?></td>
                                                    <td class="td-padding-no"><?= htmlspecialchars($row['name']) ?></td>
                                                    <td class="td-padding-no"><?= isset($row['status']) ? htmlspecialchars($row['status']) : '' ?></td>
                                                    <td class="td-padding-no" style="text-align:center;">
                                                        <span style="gap:2px;width: 100%;text-align:center;" class="d-flex">
                                                            <a href="?edit=<?= $row['id'] ?>" title="Edit"><i class="fa fa-edit text-warning mx-1"></i></a>
                                                            <a href="?delete=<?= $row['id'] ?>" title="Delete" onclick="return confirm('Are you sure you want to delete this record?');"><i class="fa fa-trash text-danger mx-1"></i></a>
                                                        </span>
                                                    </td>
                                                    <td></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="8" class="text-center">No records found.</td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                            <!-- Pagination -->
                            <?php if ($total_pages > 1): ?>
                                <nav aria-label="Page navigation">
                                    <ul class="pagination justify-content-center">
                                        <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                                            <a class="page-link" href="?page=<?= $page - 1 ?>" aria-label="Previous">
                                                <span aria-hidden="true">&laquo;</span>
                                            </a>
                                        </li>
                                        <?php
                                        $max_links = 5;
                                        $start = max(1, $page - intval($max_links / 2));
                                        $end = min($total_pages, $start + $max_links - 1);
                                        if ($end - $start + 1 < $max_links) {
                                            $start = max(1, $end - $max_links + 1);
                                        }
                                        for ($i = $start; $i <= $end; $i++): ?>
                                            <li class="page-item <?= ($i == $page) ? 'active' : '' ?>"><a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a></li>
                                        <?php endfor; ?>
                                        <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                                            <a class="page-link" href="?page=<?= $page + 1 ?>" aria-label="Next">
                                                <span aria-hidden="true">&raquo;</span>
                                            </a>
                                        </li>
                                    </ul>
                                </nav>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- CSV Preview Modal -->
                <div class="modal fade" style="width: 100%;" id="csvPreviewModal" tabindex="-1" role="dialog" aria-labelledby="csvPreviewModalLabel" aria-hidden="true">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="csvPreviewModalLabel">CSV Preview</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                           
                            <div class="modal-body">
                            <div class="table-responsive">
                                <table class="table table-bordered" id="csvPreviewTable">
                                    <tbody>
                                        <?php foreach ($preview_data as $row): ?>
                                            <tr>
                                                <td><?= htmlspecialchars($row[0]) ?></td>
                                                <td><?= htmlspecialchars($row[1]) ?></td>
                                                <td><?= htmlspecialchars($row[2]) ?></td>
                                                <td><?= htmlspecialchars($row[3]) ?></td>
                                                <td><?= htmlspecialchars($row[4]) ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <?php
            // Include footer
            $title = "Php Header Footer";
            include "footer.php";
        ?>
    </div>
    <!-- Add these first -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    <!-- Then your existing scripts -->
    <script src="assets/vendor/global/global.min.js"></script>
    <script src="assets/vendor/bootstrap-datepicker-master/js/bootstrap-datepicker.min.js"></script>
    <script src="assets/vendor/apexchart/apexchart.js"></script>
    <script src="assets/vendor/chartjs/chart.bundle.min.js"></script>
    <script src="assets/vendor/peity/jquery.peity.min.js"></script>
    <script src="assets/js/dashboard/dashboard-1.js"></script>
    <script src="assets/vendor/owl-carousel/owl.carousel.js"></script>
    <script src="assets/js/jquery.localizationTool.js"></script>
    <script src="assets/js/translator.js"></script>    
    <script src="assets/js/custom.min.js"></script>
    <script src="assets/js/dlabnav-init.js"></script>
    <script src="assets/js/demo.js"></script>

    <script>
        document.querySelector('input[type="file"]').addEventListener('change', function(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const contents = e.target.result;
                    const rows = contents.split('\n').slice(0, 5); // Get first 5 rows for preview
                    const tableBody = document.querySelector('#csvPreviewTable tbody');
                    tableBody.innerHTML = ''; // Clear previous data

                    rows.forEach(row => {
                        const cols = row.split(',');
                        const tr = document.createElement('tr');
                        cols.forEach(col => {
                            const td = document.createElement('td');
                            td.textContent = col.trim();
                            tr.appendChild(td);
                        });
                        tableBody.appendChild(tr);
                    });

                    // Show the modal
                    $('#csvPreviewModal').modal('show');
                };
                reader.readAsText(file);
            }
        });
    </script>
</body>
</html>
<?php $conn->close(); ?>
