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

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

// Add Sample
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $doctor_ids = $_POST['doctor_id'] ?? [];
    $product_id = (int)$_POST['product_id'];
    $qty        = (int)$_POST['quantity'];

    $stmt = $conn->prepare("
        INSERT INTO doctor_samples (doctor_id, product_id, quantity)
        VALUES (?, ?, ?)
    ");

    foreach ($doctor_ids as $doctor_id) {
        $doctor_id = (int)$doctor_id;
        if ($doctor_id > 0) {
            $stmt->bind_param("iii", $doctor_id, $product_id, $qty);
            $stmt->execute();
        }
    }

    header("Location: doctor_transactions.php?msg=added");
    exit;
}

// Fetch Doctors
$doctors = $conn->query("SELECT id, name FROM doctors ORDER BY name ASC");

// Fetch Sample Products
$products = $conn->query("SELECT id, product_name FROM sample_products ORDER BY product_name ASC");

// Fetch Sample History
$samples = $conn->query("
    SELECT ds.*, 
           d.name AS doctor_name, 
           p.product_name AS product_name
    FROM doctor_samples ds
    JOIN doctors d ON ds.doctor_id = d.id
    JOIN sample_products p ON ds.product_id = p.id
    ORDER BY ds.id DESC
");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Doctor Samples</title>
   <style>
body {
    color: #000;
    margin: 0;
    font-family: Arial, sans-serif;
    background: #f5f6fa;
}

/* ===== MAIN CONTENT ===== */
.main-content {
    margin-left: 250px;
    padding: 20px;
}

/* ===== CARD ===== */
.container {
    background: #fff;
    padding: 18px;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.multi-select-box{
    position: relative;
    width: 290px;
}

.select-box{
    border:1px solid #ccc;
    border-radius:8px;
    padding:10px 12px;
    background:#fff;
    cursor:pointer;
    min-height:42px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    font-size:14px;
}

.checkbox-area{
    display:none;
    position:absolute;
    top:100%;
    left:0;
    right:0;
    background:#fff;
    border:1px solid #ccc;
    border-radius:8px;
    max-height:220px;
    overflow-y:auto;
    z-index:999;
    box-shadow:0 8px 18px rgba(0,0,0,.08);
    padding:8px;
}

.checkbox-area label{
    display:flex;
    align-items:center;
    gap:8px;
    padding:8px;
    cursor:pointer;
    border-radius:6px;
}

.checkbox-area label:hover{
    background:#f1f5f9;
}

.checkbox-area input{
    width:auto;
    height:auto;
}

.multi-select-box.active .checkbox-area{
    display:block;
}
/* ===== HEADINGS ===== */
h2 {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 12px;
}

h3 {
    font-size: 16px;
    margin-top: 20px;
    margin-bottom: 10px;
}

/* ===== FORM ===== */
form {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 18px;
}

/* ===== INPUTS ===== */
select, input {
    height: 38px;
    padding: 0 10px;
    font-size: 13.5px;
    border: 1px solid #ccc;
    border-radius: 6px;
}

/* ===== BUTTON ===== */
button {
    height: 38px;
    padding: 0 14px;
    font-size: 13.5px;
    border: none;
    background: #374155;
    color: white;
    border-radius: 6px;
    cursor: pointer;
}

button:hover {
    background: #2c3445;
}

/* ===== TABLE ===== */
table {
    width: 100%;
    border-collapse: collapse;
    min-width: 600px; /* important for scroll */
}

/* TABLE WRAPPER (SCROLL FIX) */
.table-wrapper {
    width: 100%;
    overflow-x: auto;
}

/* HEADER */
th {
    background: #374155;
    color: #fff;
    font-size: 13px;
    padding: 10px;
    text-align: left;
}

/* ROWS */
td {
    padding: 10px;
    font-size: 13.5px;
}

tr {
    border-bottom: 1px solid #eee;
}

tr:hover {
    background: #f1f5f9;
}

/* ================= MOBILE RESPONSIVE ================= */
@media (max-width: 768px) {

    /* REMOVE SIDEBAR SPACE */
    .main-content {
        margin-left: 0 !important;
        padding: 12px;
    }

    /* FORM STACK */
    form {
        flex-direction: column;
        align-items: stretch;
    }

    select, input, button {
        width: 100%;
    }

    /* SMALL TEXT */
    h2 {
        font-size: 16px;
    }

    h3 {
        font-size: 14px;
    }

    /* TABLE SCROLL */
    .table-wrapper {
        overflow-x: auto;
    }

    table {
        min-width: 600px;
    }
}
</style>
</head>
<body>

<?php include 'salesmanagersidebar.php'; ?>
<?php include '../header.php'; ?>

<div class="main-content">
    <div class="container">
        <h2 style="color:#000;">
  <i class="fa-solid fa-user-doctor" style="margin-right:8px;"></i>
  Doctor Samples
</h2>

        <?php if (isset($_GET['msg']) && $_GET['msg'] === 'added'): ?>
            <p style="color:green;"></p>
        <?php endif; ?>

        <form method="POST">
<div class="multi-select-box" id="multiSelectBox">
    <div class="select-box" onclick="toggleDropdown()">
        <span id="selectedText">Select Doctor / Multiple Address</span>
        <span>▼</span>
    </div>

    <div class="checkbox-area">
        <?php while ($d = $doctors->fetch_assoc()): ?>
            <label>
                <input type="checkbox" name="doctor_id[]" value="<?php echo $d['id']; ?>" onchange="updateSelectedDoctors()">
                <?php echo htmlspecialchars($d['name']); ?>
            </label>
        <?php endwhile; ?>
    </div>
</div>

            <select name="product_id" required>
                <option value="">Select Sample Product</option>
                <?php while ($p = $products->fetch_assoc()): ?>
                    <option value="<?php echo $p['id']; ?>">
                        <?php echo htmlspecialchars($p['product_name']); ?>
                    </option>
                <?php endwhile; ?>
            </select>

            <input type="number" name="quantity" placeholder="Qty" required>

            <button type="submit">Give Sample</button>
        </form>

        <h3 style="color:#000;"> Sample History</h3>
<div class="table-wrapper">
        <table>
            <tr>
                <th>ID</th>
                <th>Doctor</th>
                <th>Product</th>
                <th>Quantity</th>
                <th>Date</th>
            </tr>

            <?php while ($row = $samples->fetch_assoc()): ?>
            <tr>
                <td><?php echo $row['id']; ?></td>
                <td><?php echo htmlspecialchars($row['doctor_name']); ?></td>
                <td><?php echo htmlspecialchars($row['product_name']); ?></td>
                <td><?php echo $row['quantity']; ?></td>
                <td><?php echo date('d-m-Y', strtotime($row['created_at'])); ?></td>
            </tr>
            <?php endwhile; ?>
        </table>
        </div>
    </div>
</div>
<script>
function toggleDropdown() {
    document.getElementById("multiSelectBox").classList.toggle("active");
}

function updateSelectedDoctors() {
    let checked = document.querySelectorAll('input[name="doctor_id[]"]:checked');
    let names = [];

    checked.forEach((item) => {
        names.push(item.parentElement.textContent.trim());
    });

    document.getElementById("selectedText").innerText =
        names.length > 0 ? names.join(', ') : "Select Doctor / Multiple Address";
}

document.addEventListener("click", function(e){
    let box = document.getElementById("multiSelectBox");
    if (!box.contains(e.target)) {
        box.classList.remove("active");
    }
});
</script>
</body>
</html>