<?php
include 'db.php';
include '../includes/auth.php';
include 'header.php';

$error = '';
$success = '';

// Handle Add or Edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = !empty($_POST['id']) ? intval($_POST['id']) : null;
    $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;

    if($id) {
        // Update
        $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();
        $success = $ok ? "Service updated successfully!" : "Update failed: ".$conn->error;
    } else {
        // Add
        $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();
        $success = $ok ? "Service added successfully!" : "Insert failed: ".$conn->error;
    }
}

// Handle Delete
if(isset($_GET['delete'])){
    $id = intval($_GET['delete']);
    $ok = $conn->query("DELETE FROM services WHERE id=$id");
    $success = $ok ? "Service deleted successfully!" : "Delete failed!";
}

// Handle Toggle 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");
    }
    header("Location: ADD_SERVICE.PHP");
    exit();
}

// Messages after delete
if(!empty($_GET['msg']) && $_GET['msg']=='deleted') $success='Service deleted successfully!';

// Fetch departments and services
$deps = $conn->query("SELECT id, name FROM departments ORDER BY name ASC");
$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>Add / Edit Service</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<!-- TinyMCE -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
function initTinyMCE() {
    if(tinymce.get('description')) tinymce.get('description').remove();
    if(tinymce.get('preparation')) tinymce.get('preparation').remove();

    tinymce.init({
        selector:'#description, #preparation',
        height:350,
        plugins:'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table emoticons wordcount',
        toolbar:'undo redo | formatselect | fontsizeselect | fontselect | 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,
        
        // Load Poppins inside TinyMCE iframe and make it default
        content_style: "@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap'); body { font-family: 'Poppins', sans-serif; font-size:14px; }",

        // Make Poppins appear in the font dropdown
        font_formats: "Poppins=Poppins,sans-serif; Arial=arial,helvetica,sans-serif; Courier New=courier new,courier,monospace; Georgia=georgia,palatino,serif; Times New Roman=times new roman,times; Verdana=verdana,geneva,sans-serif"
    });
}

document.addEventListener('DOMContentLoaded', initTinyMCE);
</script>
<style>
body { font-family: "Segoe UI", sans-serif; background:#f4f6f8; margin:0; padding:0; }
.container { max-width: 950px; width:95%; margin:40px auto; background:#fff; padding:35px 40px; border-radius:12px; box-shadow:0 10px 30px rgba(0,0,0,0.08); }
h2, h3 { color:#1a237e; }
h2 { text-align:center; margin-bottom:30px; }
.notice { padding:12px 15px; border-radius:8px; margin-bottom:25px; font-size:0.95rem; }
.notice.error { background:#f8d7da; color:#721c24; }
.notice.success { background:#d4edda; color:#155724; }
form { display:flex; flex-direction:column; gap:20px; }
.form-row { display:flex; gap:20px; flex-wrap:wrap; }
.form-row-full { width:100%; }
label { font-weight:600; margin-bottom:8px; display:block; color:#333; }
input[type="text"], input[type="number"], select, textarea { width:100%; padding:12px 14px; border-radius:8px; border:1px solid #ccc; font-size:14px; transition:0.2s; }
input:focus, select:focus, textarea:focus { border-color:#17a2b8; box-shadow:0 0 6px rgba(23,162,184,0.3); outline:none; }
.tox-tinymce { border-radius:8px !important; }
.btn { font-weight:600; padding:10px 18px; border-radius:8px; cursor:pointer; transition:0.2s; text-decoration:none; color:#fff; }
.btn-save { background:#28a745; border:none; } .btn-save:hover { background:#218838; }
.btn-cancel { background:#6c757d; border:none; margin-right:10px; } .btn-cancel:hover { background:#5a6268; }
input[type="checkbox"]{ margin-right:6px; }
.table { width:100%; border-collapse:collapse; margin-top:20px; }
.table th, .table td { padding:10px 8px; border-bottom:1px solid #eee; text-align:left; font-size:14px; }
.table th { background:#f7f8fb; font-weight:700; }
.table a.btn { font-size:0.85rem; padding:6px 10px; border-radius:6px; text-decoration:none; }
@media(max-width:780px){ .form-row{ flex-direction:column; } }
</style>
</head>
<body>
<div class="container">
    <h2 id="formTitle">Add New Service</h2>

    <?php if(!empty($error)): ?>
        <div class="notice error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    <?php if(!empty($success)): ?>
        <div class="notice success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="POST" id="serviceForm">
        <input type="hidden" name="id" id="serviceId" value="">
        <div class="form-row">
            <div>
                <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>Code</label>
                <input type="text" name="code" id="code" />
            </div>
        </div>
        <div class="form-row">
            <div>
                <label>Test Name</label>
                <input type="text" name="test_name" id="test_name" required />
            </div>
            <div>
                <label>Volume</label>
                <input type="text" name="volume" id="volume" />
            </div>
        </div>
        <div class="form-row">
            <div>
                <label>Tube / Container</label>
                <input type="text" name="tube_container" id="tube_container" />
            </div>
            <div>
                <label>Reporting Time</label>
                <input type="text" name="reporting_time" id="reporting_time" />
            </div>
        </div>
        <div class="form-row">
            <div>
                <label>Price</label>
                <input type="number" step="0.01" name="price" id="price" />
            </div>
            <div style="margin-top:30px;">
                <label><input type="checkbox" name="is_price_visible" id="is_price_visible" checked> Show Price</label>
            </div>
        </div>
        <div class="form-row-full">
            <label>Description</label>
            <textarea name="description" id="description"></textarea>
        </div>
        <div class="form-row-full">
            <label>Preparation</label>
            <textarea name="preparation" id="preparation"></textarea>
        </div>
        <div style="text-align:right; margin-top:12px;">
            <a href="ADD_SERVICE.PHP" class="btn btn-cancel">Cancel</a>
            <button type="submit" class="btn btn-save" id="saveBtn">Save</button>
        </div>
    </form>

    <h3>Existing Services</h3>
    <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="min-width:200px">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if($services && $services->num_rows>0): $i=1; ?>
                <?php while($s=$services->fetch_assoc()): ?>
                <tr style="<?= $s['is_visible'] ? '' : 'opacity:0.6; filter:grayscale(50%);' ?>">
                    <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 style="display:flex; gap:6px;">
                        <a href="#" class="btn btn-save editBtn"
                           data-id="<?= $s['id'] ?>"
                           data-department="<?= $s['department_id'] ?>"
                           data-code="<?= htmlspecialchars($s['code'], ENT_QUOTES) ?>"
                           data-test="<?= htmlspecialchars($s['test_name'], ENT_QUOTES) ?>"
                           data-volume="<?= htmlspecialchars($s['volume'], ENT_QUOTES) ?>"
                           data-tube="<?= htmlspecialchars($s['tube_container'], ENT_QUOTES) ?>"
                           data-report="<?= htmlspecialchars($s['reporting_time'], ENT_QUOTES) ?>"
                           data-price="<?= htmlspecialchars($s['price'], ENT_QUOTES) ?>"
                           data-description="<?= htmlspecialchars($s['description'], ENT_QUOTES) ?>"
                           data-preparation="<?= htmlspecialchars($s['preparation'], ENT_QUOTES) ?>"
                           data-price-visible="<?= $s['is_price_visible'] ?>"
                        >Edit</a>
                        <a href="ADD_SERVICE.PHP?delete=<?= $s['id'] ?>" class="btn btn-cancel" onclick="return confirm('Delete this service?');">Delete</a>
                        <a href="ADD_SERVICE.PHP?toggle=<?= $s['id'] ?>" class="btn btn-cancel" style="background:#17a2b8;"><?= $s['is_visible']?'Hide':'Show' ?></a>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="9" style="text-align:center; padding:15px;">No services found.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
// Populate Edit form
document.querySelectorAll('.editBtn').forEach(btn=>{
    btn.addEventListener('click', e=>{
        e.preventDefault();
        document.getElementById('formTitle').textContent='Edit Service';
        document.getElementById('serviceId').value = btn.dataset.id;
        document.getElementById('department_id').value = btn.dataset.department;
        document.getElementById('code').value = btn.dataset.code;
        document.getElementById('test_name').value = btn.dataset.test;
        document.getElementById('volume').value = btn.dataset.volume;
        document.getElementById('tube_container').value = btn.dataset.tube;
        document.getElementById('reporting_time').value = btn.dataset.report;
        document.getElementById('price').value = btn.dataset.price;
        document.getElementById('is_price_visible').checked = btn.dataset.priceVisible==1;

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