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

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];

    if ($action === 'add') {
        $name = $_POST['name'];
        $phone = $_POST['phone'];

        $stmt = $conn->prepare("INSERT INTO marketing_persons (name, phone, status, branch_id, created_at) VALUES (?, ?, 'active', ?, NOW())");
        $stmt->bind_param("ssi", $name, $phone, $branch_id);
        echo $stmt->execute() ? "Marketing person added." : "Error: " . $stmt->error;
        exit();
    }

    if ($action === 'edit') {
        $id = $_POST['id'];
        $name = $_POST['name'];
        $phone = $_POST['phone'];

        $stmt = $conn->prepare("UPDATE marketing_persons SET name=?, phone=? WHERE id=? AND branch_id=?");
        $stmt->bind_param("ssii", $name, $phone, $id, $branch_id);
        echo $stmt->execute() ? "Updated successfully." : "Error: " . $stmt->error;
        exit();
    }

    if ($action === 'delete') {
        $id = $_POST['id'];
        $stmt = $conn->prepare("UPDATE marketing_persons SET status='inactive' WHERE id=? AND branch_id=?");
        $stmt->bind_param("ii", $id, $branch_id);
        echo $stmt->execute() ? "Deleted." : "Error: " . $stmt->error;
        exit();
    }
}

// Fetch data
$result = $conn->query("SELECT id, name, phone FROM marketing_persons WHERE status='active' AND branch_id='$branch_id'");

?>
<!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>

</head>

<body>

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

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

<?php include('../config/sidebar.php'); ?>

<main id="main" class="main">
    <div class="container mt-5">
        <h2>Marketing Person Master</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMpersonModal">
  Add Marketing Person
</button>


        <table class="table datatable mt-3">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Phone</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
  <td data-label="Name"><?= htmlspecialchars($row['name']) ?></td>
  <td data-label="Phone"><?= htmlspecialchars($row['phone']) ?></td>
  <td data-label="Actions">
    <button class="btn btn-warning btn-sm" onclick="editMP(<?= $row['id'] ?>, '<?= $row['name'] ?>', '<?= $row['phone'] ?>')">Edit</button>
    <button class="btn btn-danger btn-sm" onclick="deleteMP(<?= $row['id'] ?>)">Delete</button>
  </td>
</tr>

                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</main>

<!-- Add Modal -->
<div class="modal fade" id="addMpersonModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Marketing Person</h5>
                <button class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addMPForm">
                    <input type="text" class="form-control mb-2" name="name" placeholder="Name" required>
                    <input type="text" class="form-control mb-2" name="phone" placeholder="Phone" required>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button class="btn btn-primary" onclick="submitMPForm('add')">Save</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editMPModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Marketing Person</h5>
                <button class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editMPForm">
                    <input type="hidden" name="id" id="editId">
                    <input type="text" class="form-control mb-2" name="name" id="editName" placeholder="Name" required>
                    <input type="text" class="form-control mb-2" name="phone" id="editPhone" placeholder="Phone" required>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button class="btn btn-primary" onclick="submitMPForm('edit')">Update</button>
            </div>
        </div>
    </div>
</div>

<script>
function submitMPForm(action) {
    let form = action === 'add' ? document.getElementById('addMPForm') : document.getElementById('editMPForm');
    let formData = new FormData(form);
    formData.append('action', action);

    fetch('mperson_master.php', {
        method: 'POST',
        body: formData
    }).then(res => res.text()).then(data => {
        alert(data);
        location.reload();
    });
}

function editMP(id, name, phone) {
    document.getElementById('editId').value = id;
    document.getElementById('editName').value = name;
    document.getElementById('editPhone').value = phone;
    new bootstrap.Modal(document.getElementById('editMPModal')).show();
}

function deleteMP(id) {
    if (confirm("Are you sure?")) {
        let formData = new FormData();
        formData.append('action', 'delete');
        formData.append('id', id);

        fetch('mperson_master.php', {
            method: 'POST',
            body: formData
        }).then(res => res.text()).then(data => {
            alert(data);
            location.reload();
        });
    }
}
</script>
 <!-- ======= Footer ======= -->
  

  <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>


<script>
  document.addEventListener("DOMContentLoaded", function () {
    const tables = document.querySelectorAll(".responsive-table");

    tables.forEach(table => {
      const headers = Array.from(table.querySelectorAll("thead th")).map(th => th.textContent.trim());
      const rows = table.querySelectorAll("tbody tr");

      rows.forEach(row => {
        const cells = row.querySelectorAll("td");
        cells.forEach((cell, i) => {
          if (headers[i]) {
            cell.setAttribute("data-label", headers[i]);
          }
        });
      });
    });
  });
</script>


<?php include('../config/footer.php'); ?>
