<?php
// manage_services.php

include 'db.php';

/* =========================
   EXPORT TO EXCEL
========================= */
if (isset($_GET['export']) && $_GET['export'] == 1) {

    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=services_" . date('Y-m-d') . ".xls");
    header("Pragma: no-cache");
    header("Expires: 0");

    echo "<table border='1'>";
    echo "<tr>
            <th>#</th>
            <th>Department</th>
            <th>Code</th>
            <th>Test Name</th>
            <th>Volume</th>
            <th>Tube Container</th>
            <th>Reporting Time</th>
            <th>Price (AFN)</th>
            <th>Visible</th>
            <th>Price Visible</th>
            <th>Description</th>
            <th>Preparation</th>
          </tr>";

    $services_export = $conn->query("
        SELECT s.*, d.name AS dept_name
        FROM services s
        LEFT JOIN departments d ON s.department_id=d.id
        ORDER BY s.id ASC
    ");

    $i = 1;

    while ($row = $services_export->fetch_assoc()) {

        echo "<tr>";
        echo "<td>" . $i++ . "</td>";
        echo "<td>" . ($row['dept_name'] ?? '-') . "</td>";
        echo "<td>" . $row['code'] . "</td>";
        echo "<td>" . $row['test_name'] . "</td>";
        echo "<td>" . $row['volume'] . "</td>";
        echo "<td>" . $row['tube_container'] . "</td>";
        echo "<td>" . $row['reporting_time'] . "</td>";
        echo "<td>" . $row['price'] . "</td>";
        echo "<td>" . ($row['is_visible'] ? 'Yes' : 'No') . "</td>";
        echo "<td>" . ($row['is_price_visible'] ? 'Yes' : 'No') . "</td>";
        echo "<td>" . strip_tags($row['description']) . "</td>";
        echo "<td>" . strip_tags($row['preparation']) . "</td>";
        echo "</tr>";
    }

    echo "</table>";
    exit;
}

/* AFTER EXPORT */
include '../includes/auth.php';
include 'header.php';


// Add service
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $dept = !empty($_POST['department_id']) ? intval($_POST['department_id']) : null;
    $code = trim($_POST['code']);
    $test_name = trim($_POST['test_name']);
    $description = $_POST['description'];
    $tube = trim($_POST['tube_container']);
    $volume = trim($_POST['volume']);
    $reporting = trim($_POST['reporting_time']);
    $price = floatval($_POST['price']);
    $preparation = $_POST['preparation'];
    $is_price_visible = isset($_POST['is_price_visible']) ? 1 : 0;

    $stmt = $conn->prepare("INSERT INTO services (department_id, code, test_name, description, tube_container, volume, reporting_time, price, preparation, is_price_visible) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("issssssdsi", $dept, $code, $test_name, $description, $tube, $volume, $reporting, $price, $preparation, $is_price_visible);
    $ok = $stmt->execute();
    $stmt->close();

    if ($ok) {
        header("Location: manage_services.php?msg=added");
        exit;
    } else {
        $error = "Insert failed: " . $conn->error;
    }
}

// Update service
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit') {
    $id = intval($_POST['id']);
    $dept = !empty($_POST['department_id']) ? intval($_POST['department_id']) : null;
    $code = trim($_POST['code']);
    $test_name = trim($_POST['test_name']);
    $description = $_POST['description'];
    $tube = trim($_POST['tube_container']);
    $volume = trim($_POST['volume']);
    $reporting = trim($_POST['reporting_time']);
    $price = floatval($_POST['price']);
    $preparation = $_POST['preparation'];
    $is_price_visible = isset($_POST['is_price_visible']) ? 1 : 0;

    $stmt = $conn->prepare("UPDATE services SET department_id=?, code=?, test_name=?, description=?, tube_container=?, volume=?, reporting_time=?, price=?, preparation=?, is_price_visible=? WHERE id=?");
    $stmt->bind_param("issssssdiii", $dept, $code, $test_name, $description, $tube, $volume, $reporting, $price, $preparation, $is_price_visible, $id);
    $ok = $stmt->execute();
    $stmt->close();

    if ($ok) {
        header("Location: manage_services.php?msg=updated");
        exit;
    } else {
        $error = "Update failed: " . $conn->error;
    }
}

// Delete service
if (isset($_GET['delete'])) {

    $id = intval($_GET['delete']);

    $conn->query("DELETE FROM services WHERE id=$id");

    echo "<script>
            window.location.href = 'manage_services.php?msg=deleted';
          </script>";
    exit();
}

// Toggle service visibility
if (isset($_GET['toggle'])) {

    $id = intval($_GET['toggle']);

    $row = $conn->query("SELECT is_visible FROM services WHERE id=$id")->fetch_assoc();

    if ($row) {
        $new = $row['is_visible'] ? 0 : 1;
        $conn->query("UPDATE services SET is_visible=$new WHERE id=$id");
    }

    echo "<script>
            window.location.href = 'manage_services.php';
          </script>";
    exit();
}


// Toggle price visibility
if (isset($_GET['toggle_price'])) {

    $id = intval($_GET['toggle_price']);

    $row = $conn->query("SELECT is_price_visible FROM services WHERE id=$id")->fetch_assoc();

    if ($row) {
        $new = $row['is_price_visible'] ? 0 : 1;
        $conn->query("UPDATE services SET is_price_visible=$new WHERE id=$id");
    }

    echo "<script>
            window.location.href = 'manage_services.php';
          </script>";
    exit();
}



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

// Fetch services
$services = $conn->query("SELECT s.*, d.name AS dept_name FROM services s LEFT JOIN departments d ON s.department_id=d.id ORDER BY s.id DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Manage Services</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<a class="btn" href="manage_services.php?export=1" style="background:#17a2b8">Export to Excel</a>

<!-- Full-feature TinyMCE (No API Key Needed) --><!-- Modal CSS -->
<style>
.modal {
  position: fixed;
  inset: 0;
  opacity: 0;
  visibility: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0,0,0,0.5);
  transition: opacity 0.2s ease;
  z-index: 9999;
}

.modal.open {
  opacity: 1;
  visibility: visible;
}

.modal-content {
  background:#fff;
  width: 90%;
  max-width: 1000px;
  max-height: 90vh;
  overflow-y: auto;
  padding: 20px;
  border-radius: 10px;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
    selector: '#description, #preparation',
    height: 400,
    plugins: 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table emoticons wordcount',
    toolbar: 'undo redo | formatselect | fontsizeselect | bold italic underline strikethrough | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media table | emoticons | removeformat | code fullscreen',
    menubar: 'file edit view insert format tools table help',
    branding: false,
    content_style: "body { font-family:Arial,sans-serif; font-size:14px }",
    
    // Fix dropdowns inside scrollable modal
    fixed_toolbar_container: document.body, // move toolbar outside modal
    menu_toolbar: true, // ensure menus render in body
    popup_css: true,    // make popups clickable
});
</script>



<style>
/* --- Your existing CSS styles --- */
.container { 
    max-width: 1400px;   /* wider page */
    width: 95%;
    margin: 30px auto; 
    font-family: "Segoe UI", sans-serif; 
}

.header { display:flex; justify-content:space-between; align-items:center; margin-bottom:18px; }
.header h2 { color:#1a237e; margin:0; }
.btn { display:inline-block; background:#007bff; color:#fff; padding:8px 12px; border-radius:6px; text-decoration:none; margin-right:4px;}
.table { width:100%; border-collapse:collapse; background:#fff; box-shadow:0 4px 12px rgba(0,0,0,0.05); border-radius:6px; overflow:hidden; }
.table th, .table td { padding:12px 10px; border-bottom:1px solid #eee; text-align:left; vertical-align:middle; }
.table th { background:#f7f8fb; color:#333; font-weight:700; }
.actions {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}

.actions a {
    text-decoration:none;
    padding:7px 12px;
    border-radius:6px;
    color:#fff;
    font-size:0.85rem;
    white-space: nowrap;
}

.edit { background:#28a745; } .edit:hover { background:#1e7e34; }
.delete { background:#dc3545; } .delete:hover { background:#b02a37; }
.toggle { background:#6c757d; } .toggle:hover { background:#5a6268; }
.hidden { opacity:0.6; filter:grayscale(50%); }
.notice { margin:10px 0; padding:8px 12px; border-radius:6px; }
.success { background:#d4edda; color:#155724; }
.error { background:#f8d7da; color:#721c24; }
.modal { position:fixed; inset:0; display:none; align-items:center; justify-content:center; background:rgba(0,0,0,0.5); z-index:9999; }
.modal.open { display:flex; }
.modal-content { 
    background:#fff; 
    width:100%; 
    max-width:1000px;   /* wider modal */
    max-height:90vh;    /* 👈 key fix */
    overflow-y:auto;    /* 👈 scroll inside modal */
    padding:20px; 
    border-radius:10px; 
    box-shadow:0 10px 30px rgba(0,0,0,0.2); 
    position:relative; 
}

.modal-close { position:absolute; top:10px; right:12px; cursor:pointer; font-size:1.2rem; }
.form-row { display:grid; grid-template-columns: 1fr 1fr; gap:12px; margin-bottom:12px; }
.form-row-full { margin-bottom:12px; }
.label { font-weight:600; margin-bottom:6px; color:#333; display:block; }
.small { font-size:0.9rem; color:#666; }
@media(max-width:780px){ .form-row { grid-template-columns: 1fr; } .table th, .table td { font-size:0.9rem; } }
</style>
</head>
<body>
<div class="container">
    <div class="header">
        <h2>Manage Services</h2>
        <div>
            <a class="btn" id="openAdd">＋ Add Service</a>
            
        </div>
    </div>

    <?php if(!empty($_GET['msg'])): ?>
        <div class="notice success">
            <?php 
            if($_GET['msg']=='added') echo "Service added."; 
            elseif($_GET['msg']=='updated') echo "Service updated."; 
            elseif($_GET['msg']=='deleted') echo "Service deleted."; 
            ?>
        </div>
    <?php endif; ?>
    <?php if(!empty($error)): ?>
        <div class="notice error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <table class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>Dept</th>
                <th>Code</th>
                <th>Test Name</th>
                <th>Volume</th>
                <th>Reporting</th>
                <th>Price</th>
                <th>Visible</th>
                <th style="width:320px">Actions</th>

            </tr>
        </thead>
        <tbody>
            <?php if($services && $services->num_rows>0): $i=1;
                while($s = $services->fetch_assoc()):
                    $hiddenClass = $s['is_visible'] ? '' : 'hidden';
            ?>
            <tr class="<?= $hiddenClass ?>">
                <td><?= $i++ ?></td>
                <td><?= htmlspecialchars($s['dept_name'] ?? '—') ?></td>
                <td><?= htmlspecialchars($s['code']) ?></td>
                <td><?= htmlspecialchars($s['test_name']) ?></td>
                <td><?= htmlspecialchars($s['volume']) ?></td>
                <td><?= htmlspecialchars($s['reporting_time']) ?></td>
                <td><?= $s['is_price_visible'] ? htmlspecialchars($s['price']) : '—' ?></td>
                <td><?= $s['is_visible'] ? 'Yes' : 'No' ?></td>
                <td class="actions">
                    <a href="#" class="edit"
                       data-id="<?= $s['id'] ?>"
                       data-department_id="<?= $s['department_id'] ?>"
                       data-code="<?= htmlspecialchars($s['code'], ENT_QUOTES) ?>"
                       data-test_name="<?= htmlspecialchars($s['test_name'], ENT_QUOTES) ?>"
                       data-description="<?= htmlspecialchars($s['description'], ENT_QUOTES) ?>"
                       data-tube_container="<?= htmlspecialchars($s['tube_container'], ENT_QUOTES) ?>"
                       data-volume="<?= htmlspecialchars($s['volume'], ENT_QUOTES) ?>"
                       data-reporting_time="<?= htmlspecialchars($s['reporting_time'], ENT_QUOTES) ?>"
                       data-price="<?= htmlspecialchars($s['price'], ENT_QUOTES) ?>"
                       data-preparation="<?= htmlspecialchars($s['preparation'], ENT_QUOTES) ?>"
                       data-is_price_visible="<?= $s['is_price_visible'] ?>"
                    >Edit</a>

                    <a href="manage_services.php?delete=<?= $s['id'] ?>" class="delete" onclick="return confirm('Delete service?');">Delete</a>
                    <a href="manage_services.php?toggle=<?= $s['id'] ?>" class="toggle"><?= $s['is_visible'] ? 'Hide' : 'Show' ?></a>
                    <a href="manage_services.php?toggle_price=<?= $s['id'] ?>" class="toggle"><?= $s['is_price_visible'] ? 'Hide Price' : 'Show Price' ?></a>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="9" style="text-align:center; padding:18px;">No services found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Add/Edit Modal -->
<div class="modal" id="modalForm">
  <div class="modal-content">
    <div class="modal-close" id="closeModal">✕</div>
    <h3 id="modalTitle">Add Service</h3>

    <form id="serviceForm" method="POST">
        <input type="hidden" name="action" id="formAction" value="add">
        <input type="hidden" name="id" id="serviceId" value="">

        <div class="form-row">
            <div>
                <label class="label">Department</label>
                <select name="department_id" id="department_id">
                    <option value="">— Select department —</option>
                    <?php 
                    $deps->data_seek(0);
                    while($d = $deps->fetch_assoc()): ?>
                        <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div>
                <label class="label">Code</label>
                <input type="text" name="code" id="code" />
            </div>
        </div>

        <div class="form-row">
            <div>
                <label class="label">Test Name</label>
                <input type="text" name="test_name" id="test_name" required />
            </div>
            <div>
                <label class="label">Volume</label>
                <input type="text" name="volume" id="volume" />
            </div>
        </div>

        <div class="form-row">
            <div>
                <label class="label">Tube / Container</label>
                <input type="text" name="tube_container" id="tube_container" />
            </div>
            <div>
                <label class="label">Reporting Time</label>
                <input type="text" name="reporting_time" id="reporting_time" />
            </div>
        </div>

        <div class="form-row">
            <div>
                <label class="label">Price</label>
                <input type="number" step="0.01" name="price" id="price" />
            </div>
            <div style="margin-top:25px;">
                <label><input type="checkbox" name="is_price_visible" id="is_price_visible" checked> Show Price</label>
            </div>
        </div>

        <div class="form-row-full">
            <label class="label">Description</label>
            <textarea name="description" id="description"></textarea>
        </div>

        <div class="form-row-full">
            <label class="label">Preparation</label>
            <textarea name="preparation" id="preparation"></textarea>
        </div>

        <div style="text-align:right; margin-top:12px;">
            <button type="button" id="cancelBtn" class="btn" style="background:#6c757d">Cancel</button>
            <button type="submit" class="btn" style="background:#28a745" id="saveBtn">Save</button>
        </div>
    </form>
  </div>
</div>

<script>
// Modal logic
const modal = document.getElementById('modalForm');
const openAdd = document.getElementById('openAdd');
const closeModal = document.getElementById('closeModal');
const cancelBtn = document.getElementById('cancelBtn');
const modalTitle = document.getElementById('modalTitle');
const formAction = document.getElementById('formAction');
const serviceForm = document.getElementById('serviceForm');

openAdd.addEventListener('click', () => {
    modal.classList.add('open');
    modalTitle.textContent = 'Add Service';
    formAction.value = 'add';
    serviceForm.reset();
    document.getElementById('serviceId').value = '';
    document.getElementById('is_price_visible').checked = true;
    setTimeout(()=> { initTinyMCE(); tinymce.get('description').setContent(''); tinymce.get('preparation').setContent(''); }, 100);
});

closeModal.addEventListener('click', () => modal.classList.remove('open'));
cancelBtn.addEventListener('click', () => modal.classList.remove('open'));

// Populate edit form
document.querySelectorAll('.edit').forEach(btn => {
    btn.addEventListener('click', e => {
        e.preventDefault();
        modal.classList.add('open');
        modalTitle.textContent = 'Edit Service';
        formAction.value = 'edit';

        document.getElementById('serviceId').value = btn.dataset.id || '';
        document.getElementById('department_id').value = btn.dataset.department_id || '';
        document.getElementById('code').value = btn.dataset.code || '';
        document.getElementById('test_name').value = btn.dataset.test_name || '';
        document.getElementById('tube_container').value = btn.dataset.tube_container || '';
        document.getElementById('volume').value = btn.dataset.volume || '';
        document.getElementById('reporting_time').value = btn.dataset.reporting_time || '';
        document.getElementById('price').value = btn.dataset.price || '';
        document.getElementById('is_price_visible').checked = btn.dataset.is_price_visible == 1;

        setTimeout(()=> {
            initTinyMCE();
            tinymce.get('description').setContent(btn.dataset.description || '');
            tinymce.get('preparation').setContent(btn.dataset.preparation || '');
        }, 200);
    });
});
</script>
</body>
</html>
