<?php
session_start();
if (!isset($_SESSION['userid'])) {
    // Redirect to login page if userid is not set
    header("Location: ../index.php");
    exit(); // Always use exit after header redirection
}
include '../config.php';

// Helper function for file upload
function uploadFile($fileInput, $uploadDir = "uploads/") {
    if (!empty($_FILES[$fileInput]['name'])) {
        $fileName = basename($_FILES[$fileInput]['name']);
        $targetFilePath = $uploadDir . time() . "_" . $fileName;
        $fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));

        // Validate file type
        $allowedTypes = ['jpg', 'png', 'jpeg', 'gif', 'mp3', 'wav', 'pdf'];
        if (in_array($fileType, $allowedTypes) && $_FILES[$fileInput]['size'] < 5000000) { // Limit file size to 5MB
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            if (move_uploaded_file($_FILES[$fileInput]['tmp_name'], $targetFilePath)) {
                return $targetFilePath;
            }
        }
    }
    return null;
}

// Insert or Update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize inputs
    $staff = $_SESSION['userid'];
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $order_date = $_POST['order_date'];
    $product_category = $conn->real_escape_string($_POST['product_category']);
    $mobile = $conn->real_escape_string($_POST['mobile']);
    $order_amt = floatval($_POST['order_amt']);
    $order_form = $conn->real_escape_string($_POST['order_form']);
    $srs_text = $conn->real_escape_string($_POST['srs_text']);
    $order_tips = $conn->real_escape_string($_POST['order_tips']);
    $delivery_date = $_POST['delivery_date'];
    $bdo = $conn->real_escape_string($_POST['bdo']);
    $bdm = $conn->real_escape_string($_POST['bdm']);
    $status = $conn->real_escape_string($_POST['status']); // New status field
    $customer_name = $conn->real_escape_string($_POST['customer_name']);
    // For files, preserve existing files if not uploading new ones
    $srs_image = null;
    $srs_voice = null;
    $misc_file = null;

    if ($id > 0) {
        $sqlExisting = "SELECT srs_image, srs_voice, misc_file FROM marketing_order WHERE id = ?";
        $stmtExisting = $conn->prepare($sqlExisting);
        $stmtExisting->bind_param("i", $id);
        $stmtExisting->execute();
        $resExisting = $stmtExisting->get_result();
        if ($resExisting && $resExisting->num_rows === 1) {
            $rowEx = $resExisting->fetch_assoc();
            $existing_srs_image = $rowEx['srs_image'];
            $existing_srs_voice = $rowEx['srs_voice'];
            $existing_misc_file = $rowEx['misc_file'];
        } else {
            $existing_srs_image = $existing_srs_voice = $existing_misc_file = null;
        }
        $stmtExisting->close();
    } else {
        $existing_srs_image = $existing_srs_voice = $existing_misc_file = null;
    }

    // Upload files if new files are provided, else use existing
    $uploaded_srs_image = uploadFile('srs_image');
    $srs_image = $uploaded_srs_image !== null ? $uploaded_srs_image : $existing_srs_image;
    $uploaded_srs_voice = uploadFile('srs_voice');
    $srs_voice = $uploaded_srs_voice !== null ? $uploaded_srs_voice : $existing_srs_voice;
    $uploaded_misc_file = uploadFile('misc_file');
    $misc_file = $uploaded_misc_file !== null ? $uploaded_misc_file : $existing_misc_file;

    if ($id > 0) {
        // Update existing record
        if ($status === 'Cancelled') {
    // Insert into leads table instead of updating marketing_order
     $stmt = $conn->prepare("INSERT INTO tb_leads (customer_name, mobile , status) 
                                VALUES (?, ?, ?)");
        $stmt->bind_param("sss", 
            $customer_name, $mobile, $status);
        $stmt->execute();

    // Optionally: delete cancelled record from marketing_order
    $delete = $conn->prepare("DELETE FROM marketing_order WHERE id=?");
    $delete->bind_param("i", $id);
    $delete->execute();
} else {
    // Update in marketing_order as usual
    $stmt = $conn->prepare("UPDATE marketing_order SET order_date=?, customer_name=?, product_category=?, mobile=?, order_amt=?, order_form=?, srs_image=?, srs_text=?, srs_voice=?, order_tips=?, misc_file=?, delivery_date=?, bdo=?, bdm=?, status=? WHERE id=?");
    $stmt->bind_param("ssssdssssssssssi", 
        $order_date, $customer_name, $product_category, $mobile, $order_amt, $order_form, $srs_image, $srs_text, $srs_voice, $order_tips, $misc_file, $delivery_date, $bdo, $bdm, $status, $id);
    $stmt->execute();
}


        // Check if status is 'Order Confirmed' and order_id is not already set
        if ($status === 'Order Confirmed') {
            // Check if order_id already exists
            $checkSql = "SELECT order_id FROM marketing_order WHERE id = $id";
            $checkResult = mysqli_query($conn, $checkSql);
            $checkRow = mysqli_fetch_assoc($checkResult);

            if (empty($checkRow['order_id'])) {
                // Get current year and month
                $prefix = date("ym"); // e.g., 2506

                // Count how many 'Order Confirmed' records already have an order_id
                $countSql = "SELECT COUNT(*) AS total FROM marketing_order WHERE status='Order Confirmed' AND order_id IS NOT NULL";
                $countResult = mysqli_query($conn, $countSql);
                $countRow = mysqli_fetch_assoc($countResult);
                $count = $countRow['total']; // 0 for first, 1 for second, etc.

                // Convert count to letter (A=0, B=1, C=2...)
                $letter = chr(64 + $count); // chr(65) = 'A'

                // Generate order_id
                $order_id = $prefix . "-08" . $letter . "-" . $id;

                // Update the record with order_id
                $updateOrderIdSql = "UPDATE marketing_order SET order_id = '$order_id' WHERE id = $id";
                mysqli_query($conn, $updateOrderIdSql);
            }
        }

    } else {
       if ($status === 'Cancelled') {
        // Save in leads table instead
        $stmt = $conn->prepare("INSERT INTO tb_leads (customer_name, mobile , status) 
                                VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $customer_name, $mobile, $status);
        $stmt->execute();
    } else {
        // Save in marketing_order (as it is now)
        $stmt = $conn->prepare("INSERT INTO marketing_order (customer_name, order_date, product_category, mobile, order_amt, order_form, srs_image, srs_text, srs_voice, order_tips, misc_file, delivery_date, bdo, bdm, status, staff) 
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssdssssssssssi", 
            $customer_name, $order_date, $product_category, $mobile, $order_amt, $order_form, $srs_image, $srs_text, $srs_voice, $order_tips, $misc_file, $delivery_date, $bdo, $bdm, $status, $staff);
        $stmt->execute();
    }


        // Get insert ID
        $last_id = $conn->insert_id;

        // Check if status is 'Order Confirmed' and order_id is not already set
        if ($status === 'Order Confirmed') {
            // Check if order_id already exists
            $checkSql = "SELECT order_id FROM marketing_order WHERE id = $last_id";
            $checkResult = mysqli_query($conn, $checkSql);
            $checkRow = mysqli_fetch_assoc($checkResult);

            if (empty($checkRow['order_id'])) {
                // Get current year and month
                $prefix = date("ym"); // e.g., 2506

                // Count how many 'Order Confirmed' records already have an order_id
                $countSql = "SELECT COUNT(*) AS total FROM marketing_order WHERE status='Order Confirmed' AND order_id IS NOT NULL";
                $countResult = mysqli_query($conn, $countSql);
                $countRow = mysqli_fetch_assoc($countResult);
                $count = $countRow['total']; // 0 for first, 1 for second, etc.

                // Convert count to letter (A=0, B=1, C=2...)
                $letter = chr(65 + $count); // chr(65) = 'A'

                // Generate order_id
                $order_id = $prefix . "-08" . $letter . "-" . $last_id;

                // Update the record with order_id
                $updateOrderIdSql = "UPDATE marketing_order SET order_id = '$order_id' WHERE id = $last_id";
                mysqli_query($conn, $updateOrderIdSql);
            }
        }
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit();
}

// Delete record
if (isset($_GET['delete'])) {
    $deleteId = intval($_GET['delete']);
    $stmtDelete = $conn->prepare("DELETE FROM marketing_order WHERE id = ?");
    $stmtDelete->bind_param("i", $deleteId);
    $stmtDelete->execute();
    $stmtDelete->close();
    header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
    exit();
}

// Search functionality
$search_query = '';
if (!empty($_GET['search'])) {
    $search_input = $conn->real_escape_string($_GET['search']);
    $search_query = " WHERE order_date LIKE '%$search_input%' 
        OR product_category LIKE '%$search_input%' OR mobile LIKE '%$search_input%'
        OR bdo LIKE '%$search_input%' OR bdm LIKE '%$search_input%' ";
}

// Pagination variables
$limit = 20; // Number of records per page
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $limit;

// Adjust SQL query for pagination and sorting
$sql = "SELECT * FROM marketing_order $search_query ORDER BY id DESC LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$results = $stmt->get_result();

// Calculate total records for pagination
$total_records = mysqli_num_rows($conn->query("SELECT * FROM marketing_order $search_query"));
$total_pages = ceil($total_records / $limit);

// For editing an existing record
$edit_record = null;
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $stmtEdit = $conn->prepare("SELECT * FROM marketing_order WHERE id = ? ORDER BY id DESC");
    $stmtEdit->bind_param("i", $edit_id);
    $stmtEdit->execute();
    $resEdit = $stmtEdit->get_result();
    if ($resEdit && $resEdit->num_rows === 1) {
        $edit_record = $resEdit->fetch_assoc();
    }
    $stmtEdit->close();
}
?>
<!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/6.4.0/css/all.min.css" rel="stylesheet"/>

</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.php" 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">
                                Marketing Data
                            </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-12">
                        <div class="row">
                            <div class="col-xl-4">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="basic-form">
                                            <form method="post" enctype="multipart/form-data">
                                                <input type="hidden" name="id" value="<?php echo isset($edit_record['id']) ? $edit_record['id'] : ''; ?>" />
                                                <div class="row">
                                                    <div class="mb-2 col-md-12">
                                                        <input placeholder="Order Date" class="form-control" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="order_date" name="order_date" required value="<?php echo isset($edit_record['order_date']) ? $edit_record['order_date'] : ''; ?>" />
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="text" class="form-control" placeholder="Product Category" name="product_category" required value="<?php echo isset($edit_record['product_category']) ? htmlspecialchars($edit_record['product_category']) : ''; ?>">
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="text" class="form-control" placeholder="Customer Name" name="customer_name" required value="<?php echo isset($edit_record['customer_name']) ? htmlspecialchars($edit_record['customer_name']) : ''; ?>">
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="text" class="form-control" placeholder="Mobile No." name="mobile" required value="<?php echo isset($edit_record['mobile']) ? htmlspecialchars($edit_record['mobile']) : ''; ?>">
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="number" step="0.01" class="form-control" placeholder="Order Amt" name="order_amt" required value="<?php echo isset($edit_record['order_amt']) ? $edit_record['order_amt'] : ''; ?>">
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="text" class="form-control" placeholder="Order Form" name="order_form" value="<?php echo isset($edit_record['order_form']) ? htmlspecialchars($edit_record['order_form']) : ''; ?>">
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="file" class="form-control" id="srsFile" name="srs_image" onchange="updateFileLabel(this, 'fileLabelSRSImage')">
                                                        <small id="fileLabelSRSImage" class="form-text text-danger"><?php if(isset($edit_record['srs_image']) && $edit_record['srs_image']) echo "Current: " . basename($edit_record['srs_image']); else echo "Upload SRS (JPG/PNG)"; ?></small>
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <textarea class="form-control" rows="3" name="srs_text" placeholder="SRS Text"><?php echo isset($edit_record['srs_text']) ? htmlspecialchars($edit_record['srs_text']) : ''; ?></textarea>
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="file" class="form-control" id="srsVoice" name="srs_voice" onchange="updateFileLabel(this, 'fileLabelSRSVoice')">
                                                        <small id="fileLabelSRSVoice" class="form-text text-danger"><?php if(isset($edit_record['srs_voice']) && $edit_record['srs_voice']) echo "Current: " . basename($edit_record['srs_voice']); else echo "SRS Voice (audio)"; ?></small>
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="text" class="form-control" placeholder="Order Tips" name="order_tips" value="<?php echo isset($edit_record['order_tips']) ? htmlspecialchars($edit_record['order_tips']) : ''; ?>">
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="file" class="form-control" id="miscFile" name="misc_file" onchange="updateFileLabel(this, 'fileLabelMisc')">
                                                        <small id="fileLabelMisc" class="form-text text-danger"><?php if(isset($edit_record['misc_file']) && $edit_record['misc_file']) echo "Current: " . basename($edit_record['misc_file']); else echo "Miscellaneous (JPG/PNG)"; ?></small>
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input placeholder="Delivery Date" class="form-control" type="text" onfocus="(this.type='date')" onblur="(this.type='text                                                        )" name="delivery_date" required value="<?php echo isset($edit_record['delivery_date']) ? $edit_record['delivery_date'] : ''; ?>" />
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="text" class="form-control" placeholder="BDO" name="bdo" value="<?php echo isset($edit_record['bdo']) ? htmlspecialchars($edit_record['bdo']) : ''; ?>">
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <input type="text" class="form-control" placeholder="BDM" name="bdm" value="<?php echo isset($edit_record['bdm']) ? htmlspecialchars($edit_record['bdm']) : ''; ?>">
                                                    </div>
                                                    <div class="mb-2 col-md-12">
                                                        <select class="form-control" name="status" required>
                                                            <option value="">Select Status</option>
                                                            <option value="Order Confirmed" <?php echo (isset($edit_record['status']) && $edit_record['status'] == 'Order Confirmed') ? 'selected' : ''; ?>>Order Confirmed</option>
                                                            <option value="Completed" <?php echo (isset($edit_record['status']) && $edit_record['status'] == 'Completed') ? 'selected' : ''; ?>>Completed</option>
                                                            <option value="Cancelled" <?php echo (isset($edit_record['status']) && $edit_record['status'] == 'Cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <button type="submit" class="btn btn-primary w-100"><?php echo isset($edit_record) ? 'Update' : 'Submit'; ?></button>
                                                <?php if(isset($edit_record)): ?>
                                                <a href="index.php" class="btn btn-secondary w-100 mt-2">Cancel Edit</a>
                                                <?php endif; ?>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-xl-8">
                                <div class="row w-100 mb-2 float-right">
                                    <div class="col-md-12">
                                        <div class="row g-0" style="gap: 5px;">
                                            <form method="GET" class="d-flex gap-2 w-100">
                                                <div class="col-md-2 col-sm-3 col-3">
                                                    <input name="from_date" placeholder="From" class="w-100 " type="text" onfocus="(this.type='date')" onblur="(this.type='text')" />
                                                </div>
                                                <div class="col-md-2 col-sm-3 col-3">
                                                    <input name="to_date" placeholder="To" class="w-100 " type="text" onfocus="(this.type='date')" onblur="(this.type='text')" />
                                                </div>
                                                <div class="col-md-3 col-sm-3 col-3">
                                                    <input name="search" type="text" class="w-100" placeholder="Search product/mobile/BDO/BDM" value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
                                                </div>
                                                <div class="col-md-2 col-sm-3 col-3">
                                                    <button type="submit" class="w-100">Filter</button>
                                                </div>
                                                <div class="col-md-2 col-sm-3 col-3">
                                                    <button class="w-100" type="button" onclick="printTable()"><i class="fa fa-print"></i> Print</button> 
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-responsive-sm" id="ordersTable">
                                            <thead>
                                                <tr>
                                                    <th class="td-padding-no" style="width: 10px;">#</th>
                                                    <th class="td-padding-no" style="width: 80px;">O.Date</th>
                                                    <th class="td-padding-no">P.Cat</th>
                                                    <th class="td-padding-no">Customer</th>
                                                    <th class="td-padding-no">Mobile No.</th>
                                                    <th class="td-padding-no">O.Amt</th>
                                                    <th class="td-padding-no">O.Form</th>
                                                    <th class="td-padding-no">SRS</th>
                                                    <th class="td-padding-no">SRS Text</th>
                                                    <th class="td-padding-no">SRS Voice</th>
                                                    <th class="td-padding-no">O.Tips</th>
                                                    <th class="td-padding-no">Misc</th>
                                                    <th class="td-padding-no" style="width: 80px;">D.Date</th>
                                                    <th class="td-padding-no">BDO</th>
                                                    <th class="td-padding-no">BDM</th>
                                                    <th class="td-padding-no">Status</th>
                                                    <th class="td-padding-no" style="text-align:center; width: 80px;">Action</th>
                                                </tr>
                                            </thead>

                                            <style>
                                            .status-confirmed {
                                                background-color: #d4edda;
                                                color: #155724!important;
                                                font-weight: bold;
                                            }
                                            .td-padding-no {
                                                padding: 0;
                                                word-wrap: break-word;
                                                white-space: normal;
                                                max-width: 500px; /* adjust as needed */
                                            }
                                                                                        </style>
                                            <tbody>
                                                <?php if ($results && $results->num_rows > 0): 
                                                    $counter = $total_records - $offset; ?>
                                                    <?php while($row = $results->fetch_assoc()): ?>
                                                        <tr>
                                                            <th class="td-padding-no"><?php echo $counter--; ?></th>
                                                            <td class="td-padding-no"><?php echo htmlspecialchars($row['order_date']); ?></td>
                                                            <td class="td-padding-no"><?php echo htmlspecialchars($row['product_category']); ?></td>
                                                            <td class="td-padding-no"><?php echo htmlspecialchars($row['customer_name']); ?></td>
                                                            <td class="td-padding-no"><?php echo htmlspecialchars($row['mobile']); ?></td>
                                                            <td class="td-padding-no"><?php echo number_format($row['order_amt'], 2); ?></td>
                                                            <td class="td-padding-no"><a href="<?php echo htmlspecialchars($row['order_form']); ?>" target="_blank"><?php echo htmlspecialchars(basename($row['order_form'])); ?></a></td>
                                                            <td class="td-padding-no">
                                                                <?php if ($row['srs_image']): ?>
                                                                    <a href="<?php echo htmlspecialchars($row['srs_image']); ?>" target="_blank">File</a>
                                                                <?php else: echo '-'; endif; ?>
                                                            </td>
                                                            <td class="td-padding-no" style="max-width:200px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
    <span data-bs-toggle="modal" data-bs-target="#textModal<?php echo $row['id']; ?>" 
          style="cursor:pointer;" 
          title="Click to view full text">
        <?php echo htmlspecialchars($row['srs_text']); ?>
    </span>
</td>

<!-- Modal -->
<div class="modal fade" id="textModal<?php echo $row['id']; ?>" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content p-3">
      <div class="modal-header">
        <h5 class="modal-title">Full Text</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <?php echo nl2br(htmlspecialchars($row['srs_text'])); ?>
      </div>
    </div>
  </div>
</div>


                                                            <td class="td-padding-no"><?php echo $row['srs_voice'] ? '<a href="'.htmlspecialchars($row['srs_voice']).'" target="_blank">Voice</a>' : '-'; ?></td>
                                                            <td class="td-padding-no"><?php echo htmlspecialchars($row['order_tips']); ?></td>
                                                            <td class="td-padding-no"><?php echo $row['misc_file'] ? '<a href="'.htmlspecialchars($row['misc_file']).'" target="_blank">File</a>' : '-'; ?></td>
                                                            <td class="td-padding-no"><?php echo htmlspecialchars($row['delivery_date']); ?></td>
                                                            <td class="td-padding-no"><?php echo htmlspecialchars($row['bdo']); ?></td>
                                                            <td class="td-padding-no"><?php echo htmlspecialchars($row['bdm']); ?></td>
                                                            <?php
                                                                $statusClass = (htmlspecialchars($row['status']) == 'Order Confirmed') ? 'status-confirmed' : '';
                                                                ?>
                                                                <td class="td-padding-no <?php echo $statusClass; ?>">
                                                                    <?php echo htmlspecialchars($row['status']); ?>
                                                                </td>
                                                            <td class="td-padding-no" style="text-align:center;">
                                                                <a href="?edit=<?php echo $row['id']; ?>" class="text-warning me-1" title="Edit"><i class="fa fa-edit"></i></a>
                                                                <a href="?delete=<?php echo $row['id']; ?>" class="text-danger" onclick="return confirm('Are you sure you want to delete this order?');" title="Delete"><i class="fa fa-trash"></i></a>
                                                            <a href="workorder.php?orderid=<?php echo $row['id']; ?>" class="text-primary" title="Order Form">
    <i class="fa fa-file-alt"></i>
</a>
                                                            </td>




                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="15" class="text-center">No records found</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <nav aria-label="Page navigation">
                                            <ul class="pagination justify-content-center">
                                                <?php if ($page > 1): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?php echo $page - 1; ?>" aria-label="Previous">
                                                            <span aria-hidden="true">&laquo;</span>
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                                    <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                        <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                                    </li>
                                                <?php endfor; ?>
                                                <?php if ($page < $total_pages): ?>
                                                    <li class="page-item">
                                                        <a class="page-link" href="?page=<?php echo $page + 1; ?>" aria-label="Next">
                                                            <span aria-hidden="true">&raquo;</span>
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                            </ul>
                                        </nav>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
            $title = "Php Header Footer";                   
            include "footer.php";     
        ?>
    </div>

    <script>
        function updateFileLabel(input, labelId) {
            const label = document.getElementById(labelId);
            label.textContent = input.files.length > 0 ? input.files[0].name : 'No file chosen';
        }
        function printTable() {
            var printWindow = window.open('', '', 'height=600,width=800');
            printWindow.document.write('<html><head><title>Print</title>');
            printWindow.document.write('<link href="assets/vendor/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet"/>');
            printWindow.document.write('<link href="assets/vendor/bootstrap-datepicker-master/css/bootstrap-datepicker.min.css" rel="stylesheet"/>');
            printWindow.document.write('<style>table {width: 100%; border-collapse: collapse;} th, td {border: 1px solid #333; padding: 8px; text-align:left;} </style>');
            printWindow.document.write('</head><body >');
            printWindow.document.write('<h3>Marketing Orders</h3>');
            printWindow.document.write(document.querySelector('.table-responsive').innerHTML);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();
        }
    </script>

    <script src="assets/vendor/global/global.min.js"></script>
    <script src="assets/vendor/bootstrap-select/dist/js/bootstrap-select.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>
</body>
</html>
<?php $conn->close(); ?>
