<?php
include('../config/config.php');
include('../config/session_check.php');
$branch_id = $_SESSION['branch_id'];

$from = isset($_GET['from']) ? $_GET['from'] : date('Y-m-01');
$to = isset($_GET['to']) ? $_GET['to'] : date('Y-m-d');
$marketing_person_id = isset($_GET['mp']) ? $_GET['mp'] : '';
$group_by = isset($_GET['group_by']) && in_array($_GET['group_by'], ['customer', 'date']) ? $_GET['group_by'] : '';

$where = "WHERE o.status='active' AND o.branch_id = $branch_id AND DATE(o.execution_date) BETWEEN '$from' AND '$to'";
if (!empty($marketing_person_id)) {
    $where .= " AND o.marketing_person_id = '$marketing_person_id'";
}

$order_by = "ORDER BY m.name, o.execution_date, c.customer_name";

$query = "SELECT 
            o.order_no,
            o.execution_date,
            o.order_date,
            o.order_quantity_m3,
            c.customer_name,
            m.name as marketing_person
          FROM orders o
          JOIN customers c ON o.customer_id = c.id
          JOIN marketing_persons m ON o.marketing_person_id = m.id
          $where
          $order_by";

$results = $conn->query($query);
$data = [];
$totalOverall = 0;
$no_group_data = [];

while ($row = $results->fetch_assoc()) {
    $totalOverall += $row['order_quantity_m3'];
    if (!empty($group_by)) {
        $groupKey = ($group_by == 'date') ? date('d-m-Y', strtotime($row['execution_date'])) : $row['customer_name'];
        $mp = $row['marketing_person'];
        $data[$mp][$groupKey][] = $row;
    } else {
        $no_group_data[] = $row;
    }
}

$marketers = $conn->query("SELECT id, name FROM marketing_persons WHERE status='active' AND branch_id = $branch_id ORDER BY name ASC");

function exportCSV($grouped) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment;filename=marketing_report.csv');
    $output = fopen("php://output", "w");
    fputcsv($output, ['Marketing Person', 'order_date','Customer', 'Total Order (m³)']);
    foreach ($grouped as $mp => $rows) {
        foreach ($rows as $r) {
            fputcsv($output, [$mp, $r['customer_name'], $r['total_m3']]);
        }
    }
    fclose($output);
    exit();
}

if (isset($_GET['export']) && $_GET['export'] == 'csv') {
    exportCSV($grouped);
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>Customer Master</title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <!-- Favicons -->
  <link href="../assets/img/favicon.png" rel="icon">
  <link href="../assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

  <!-- Vendor CSS Files -->
  <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="../assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="../assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="../assets/vendor/simple-datatables/style.css" rel="stylesheet">

  <!-- Template Main CSS File -->
  <link href="../assets/css/style.css" rel="stylesheet">
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
    @media (max-width: 768px) {
        table thead { display: none; }
        table tbody tr { display: block; margin-bottom: 1rem; border: 1px solid #ccc; padding: 1rem; }
        table tbody td { display: flex; justify-content: space-between; padding: .5rem 0; border-bottom: 1px solid #ddd; }
        table tbody td:last-child { border-bottom: none; }
        table td::before { content: attr(data-label); font-weight: bold; }
    }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

  

</head>

<body>

  <!-- ======= Header ======= -->
<?php include('../config/header.php'); ?> // Include the header

  <!-- ======= Sidebar ======= -->

<?php include('../config/sidebar.php'); ?>
  
<body class="p-4">

<main id="main" class="main">
<div class="container">
  <h2 class="mt-4">Marketing Person Order Report</h2>

  <form method="GET" class="row g-3 mb-4">
    <div class="col-md-3">
        <label>From</label>
        <input type="date" name="from" class="form-control" value="<?= $from ?>">
    </div>
    <div class="col-md-3">
        <label>To</label>
        <input type="date" name="to" class="form-control" value="<?= $to ?>">
    </div>
    <div class="col-md-3">
        <label>Marketing Person</label>
        <select name="mp" class="form-control">
            <option value="">All</option>
            <?php while($mp = $marketers->fetch_assoc()): ?>
            <option value="<?= $mp['id'] ?>" <?= $marketing_person_id == $mp['id'] ? 'selected' : '' ?>><?= $mp['name'] ?></option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="col-md-3">
        <label>Group By</label>
        <select name="group_by" class="form-control">
            <option value="" <?= $group_by == '' ? 'selected' : '' ?>>None</option>
            <option value="customer" <?= $group_by == 'customer' ? 'selected' : '' ?>>Customer</option>
            <option value="date" <?= $group_by == 'date' ? 'selected' : '' ?>>Execution Date</option>
        </select>
    </div>
    <div class="col-12 d-flex gap-2">
        <button class="btn btn-primary">Filter</button>
        <button type="button" onclick="downloadPDF()" class="btn btn-danger">Export PDF</button>
        <a href="?from=<?= $from ?>&to=<?= $to ?>&mp=<?= $marketing_person_id ?>&group_by=<?= $group_by ?>&export=csv" class="btn btn-success">Export CSV</a>
    </div>
  </form>

  <div class="jumbotron bg-light p-3 mb-3 rounded shadow-sm">
    <strong>Report From:</strong> <?= date('d-m-Y', strtotime($from)) ?> 
    <strong>To:</strong> <?= date('d-m-Y', strtotime($to)) ?> | 
    <strong>Total:</strong> <?= number_format($totalOverall, 2) ?> m³
  </div>

  <div id="reportArea">
    <?php if (!empty($group_by)): ?>
      <?php foreach ($data as $mp => $groups): ?>
        <h4 class="text-primary">Marketing Person: <?= htmlspecialchars($mp) ?></h4>
        <?php foreach ($groups as $groupKey => $rows): ?>
          <h5 class="text-dark">Group: <?= htmlspecialchars($groupKey) ?></h5>
          <table class="table table-bordered table-striped">
            <thead>
              <tr>
                <th>Order No</th>
                <th>Order Date</th>
                <th>Execution Date</th>
                <th>Customer</th>
                <th>Quantity (m³)</th>
              </tr>
            </thead>
            <tbody>
              <?php 
                $subTotal = 0;
                foreach ($rows as $r): 
                $subTotal += $r['order_quantity_m3'];
              ?>
              <tr>
                <td data-label="Order No"><?= $r['order_no'] ?></td>
                <td data-label="Order Date"><?= date('d-m-Y', strtotime($r['order_date'])) ?></td>
                <td data-label="Execution Date"><?= date('d-m-Y', strtotime($r['execution_date'])) ?></td>
                <td data-label="Customer"><?= htmlspecialchars($r['customer_name']) ?></td>
                <td data-label="Quantity"><?= $r['order_quantity_m3'] ?> m³</td>
              </tr>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr class="table-secondary">
                <td colspan="4"><strong>Subtotal</strong></td>
                <td><strong><?= number_format($subTotal, 2) ?> m³</strong></td>
              </tr>
            </tfoot>
          </table>
        <?php endforeach; ?>
      <?php endforeach; ?>
    <?php else: ?>
      <h4 class="text-primary">All Orders</h4>
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>Order No</th>
            <th>Order Date</th>
            <th>Execution Date</th>
            <th>Customer</th>
            <th>Marketing Person</th>
            <th>Quantity (m³)</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($no_group_data as $r): ?>
          <tr>
            <td data-label="Order No"><?= $r['order_no'] ?></td>
            <td data-label="Order Date"><?= date('d-m-Y', strtotime($r['order_date'])) ?></td>
            <td data-label="Execution Date"><?= date('d-m-Y', strtotime($r['execution_date'])) ?></td>
            <td data-label="Customer"><?= htmlspecialchars($r['customer_name']) ?></td>
            <td data-label="Marketing Person"><?= htmlspecialchars($r['marketing_person']) ?></td>
            <td data-label="Quantity"><?= $r['order_quantity_m3'] ?> m³</td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>
</div>
</main>

<script>
function downloadPDF() {
    alert('hi');
    var element = document.getElementById("reportArea");
    html2pdf().from(element).save('marketing_report.pdf');
}
</script>

  <!-- ======= Footer ======= -->
  <?php include '../config/footer.php'; ?>

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

  <!-- Vendor JS Files -->
  <script src="../assets/vendor/apexcharts/apexcharts.min.js"></script>
  <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="../assets/vendor/chart.js/chart.umd.js"></script>
  <script src="../assets/vendor/echarts/echarts.min.js"></script>
  <script src="../assets/vendor/quill/quill.js"></script>
  <script src="../assets/vendor/simple-datatables/simple-datatables.js"></script>
  <script src="../assets/vendor/tinymce/tinymce.min.js"></script>
  <script src="../assets/vendor/php-email-form/validate.js"></script>

  <!-- Template Main JS File -->
  <script src="../assets/js/main.js"></script>
</body>
</html>