<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../../dripend/includes/db.php';

$message = '';

// ==============================================================================
// 1. HANDLE FORM SUBMISSIONS (ADD, EDIT, & TOGGLE VIA POST)
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $formulation_name = trim($_POST['formulation_name']);
        $formulation_symbol = trim($_POST['formulation_symbol']);
        $description = trim($_POST['description']);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        $stmt = $conn->prepare("INSERT INTO drug_formulations (formulation_name, formulation_symbol, description, is_active) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("sssi", $formulation_name, $formulation_symbol, $description, $is_active);
        if ($stmt->execute()) {
            $message = "<div class='alert alert-success'><i class='fa-solid fa-check-circle'></i> Formulation added successfully.</div>";
        } else {
            $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> Error: Formulation might already exist.</div>";
        }
        $stmt->close();
        
    } elseif ($action === 'edit') {
        $id = (int)$_POST['id'];
        $formulation_name = trim($_POST['formulation_name']);
        $formulation_symbol = trim($_POST['formulation_symbol']);
        $description = trim($_POST['description']);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        $stmt = $conn->prepare("UPDATE drug_formulations SET formulation_name = ?, formulation_symbol = ?, description = ?, is_active = ? WHERE id = ?");
        $stmt->bind_param("sssii", $formulation_name, $formulation_symbol, $description, $is_active, $id);
        if ($stmt->execute()) {
            $message = "<div class='alert alert-success'><i class='fa-solid fa-check-circle'></i> Formulation updated successfully.</div>";
        } else {
            $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> Error updating formulation.</div>";
        }
        $stmt->close();
        
    } elseif ($action === 'toggle') {
        $id = (int)$_POST['id'];
        $current_status = (int)$_POST['current_status'];
        $new_status = $current_status === 1 ? 0 : 1;
        
        $stmt = $conn->prepare("UPDATE drug_formulations SET is_active = ? WHERE id = ?");
        $stmt->bind_param("ii", $new_status, $id);
        if ($stmt->execute()) {
            $message = "<div class='alert alert-success'><i class='fa-solid fa-check-circle'></i> Formulation status updated successfully.</div>";
        } else {
            $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> Error toggling status.</div>";
        }
        $stmt->close();
    }
}

if (isset($_SESSION['success'])) {
    $message = "<div class='alert alert-success'><i class='fa-solid fa-check-circle'></i> " . $_SESSION['success'] . "</div>";
    unset($_SESSION['success']);
}
if (isset($_SESSION['error'])) {
    $message = "<div class='alert alert-danger'><i class='fa-solid fa-ban'></i> " . $_SESSION['error'] . "</div>";
    unset($_SESSION['error']);
}

$formulations = $conn->query("SELECT * FROM drug_formulations ORDER BY formulation_name ASC")->fetch_all(MYSQLI_ASSOC);

$kpis = ['total' => count($formulations), 'active' => 0, 'inactive' => 0];
foreach ($formulations as $f) {
    if ($f['is_active'] == 1) $kpis['active']++;
    else $kpis['inactive']++;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Formulations | Enterprise</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    :root { --sidebar-width: 240px; --e-blue: #1e3a8a; --e-green: #16a34a; --bg: #f8fafc; --border: #e2e8f0; --text: #334155; }
    body { font-family: "Segoe UI", system-ui, sans-serif; background: var(--bg); margin: 0; padding: 0; color: var(--text); overflow-x: hidden; }
    
    .page-wrapper { position: absolute; top: 0; left: var(--sidebar-width); width: calc(100% - var(--sidebar-width)); min-height: 100vh; padding: 30px; box-sizing: border-box; }
    
    .header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
    .header-bar h2 { color: var(--e-blue); margin: 0; font-size: 24px; font-weight: 800; text-transform: uppercase; display:flex; align-items:center; gap:10px; }
    .btn-add { background: var(--e-blue); color: #fff; padding: 12px 20px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; box-shadow: 0 4px 6px rgba(30,58,138,0.2); transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; }
    .btn-add:hover { background: #1e293b; transform: translateY(-2px); }

    .alert { padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; font-weight: 600; display:flex; align-items:center; gap:10px; border-left: 5px solid; }
    .alert-success { background: #dcfce7; color: #166534; border-color: #22c55e; }
    .alert-danger { background: #fee2e2; color: #991b1b; border-color: #ef4444; }

    .kpi-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 25px; }
    .kpi-card { background: #fff; padding: 20px; border-radius: 12px; border: 1px solid var(--border); border-left: 5px solid var(--e-blue); box-shadow: 0 4px 10px rgba(0,0,0,0.02); display: flex; justify-content: space-between; align-items: center; }
    .kpi-card.green { border-left-color: var(--e-green); }
    .kpi-card.red { border-left-color: #dc2626; }
    .kpi-info h3 { margin: 0 0 5px 0; font-size: 13px; color: #64748b; text-transform: uppercase; font-weight: 700; }
    .kpi-info p { margin: 0; font-size: 26px; font-weight: 800; color: #0f172a; }
    .kpi-icon { font-size: 30px; color: #e2e8f0; }

    .table-card { background: #fff; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; border: 1px solid var(--border); }
    table { width: 100%; border-collapse: collapse; }
    th { background: #f8fafc; color: #475569; padding: 15px; font-size: 12px; text-transform: uppercase; border-bottom: 2px solid var(--border); text-align: left; }
    td { padding: 15px; border-bottom: 1px solid var(--border); font-size: 14px; vertical-align: middle; }
    tr:hover { background: #f0fdf4; }
    tr.inactive { opacity: 0.6; background: #f8fafc; }
    
    .badge { padding: 4px 8px; border-radius: 6px; font-size: 11px; font-weight: 800; display: inline-flex; align-items: center; gap: 5px; }
    .bg-blue { background: #dbeafe; color: #1e40af; border: 1px solid #bfdbfe; }
    .bg-green { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
    .bg-red { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

    .action-group { display: flex; gap: 6px; justify-content: flex-end; }
    .btn-action { width: 34px; height: 34px; border-radius: 6px; border: none; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: 0.2s; font-size: 14px; }
    .btn-edit { background: #eff6ff; color: #1e40af; border: 1px solid #bfdbfe; }
    .btn-edit:hover { background: #dbeafe; }
    .btn-toggle { background: #fef3c7; color: #b45309; border: 1px solid #fde68a; }
    .btn-toggle:hover { background: #fde68a; }
    .btn-delete { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
    .btn-delete:hover { background: #fca5a5; }

    .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15,23,42,0.5); backdrop-filter: blur(3px); display: none; align-items: center; justify-content: center; z-index: 9999; opacity: 0; transition: 0.2s; }
    .modal-overlay.active { display: flex; opacity: 1; }
    .modal-card { width: 500px; background: #fff; border-radius: 12px; box-shadow: 0 20px 40px rgba(0,0,0,0.2); transform: scale(0.95); transition: 0.2s; overflow: hidden; }
    .modal-overlay.active .modal-card { transform: scale(1); }
    
    .modal-header { padding: 20px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: #f8fafc; }
    .modal-header h2 { margin: 0; color: var(--e-blue); font-size: 18px; font-weight: 800; }
    .close-modal { background: none; border: none; font-size: 20px; color: #64748b; cursor: pointer; }
    
    .modal-body { padding: 20px; }
    .form-group { margin-bottom: 15px; display: flex; flex-direction: column; gap: 5px; }
    .form-group label { font-size: 12px; font-weight: 700; color: #475569; text-transform: uppercase; }
    .form-control { padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; outline: none; }
    .form-control:focus { border-color: var(--e-blue); box-shadow: 0 0 0 3px #eff6ff; }
    
    .toggle-switch { display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 700; color: #0f172a; font-size: 14px; }
    .toggle-switch input { width: 18px; height: 18px; accent-color: var(--e-blue); cursor: pointer; }

    .modal-footer { padding: 15px 20px; background: #f8fafc; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 10px; }
    .btn-save { background: var(--e-blue); color: #fff; padding: 10px 20px; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.2s; }
    .btn-save:hover { background: #1e293b; }
    .btn-cancel { background: #e2e8f0; color: #475569; padding: 10px 20px; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; }
</style>
</head>
<body>

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

<div class="page-wrapper">

    <div style="margin-bottom:15px;">
        <a href="listMedicine.php" style="color:#64748b; text-decoration:none; font-weight:700; font-size:13px;"><i class="fa-solid fa-arrow-left"></i> Back to Master Formulary</a>
    </div>

    <div class="header-bar">
        <h2><i class="fa-solid fa-mortar-pestle"></i> Dictionary: Drug Formulations</h2>
        <button class="btn-add" onclick="openModal('add')"><i class="fa-solid fa-plus"></i> Add Formulation</button>
    </div>

    <?= $message ?>

    <div class="kpi-grid">
        <div class="kpi-card">
            <div class="kpi-info"><h3>Total Formulations</h3><p><?= $kpis['total'] ?></p></div>
            <i class="fa-solid fa-list-ul kpi-icon"></i>
        </div>
        <div class="kpi-card green">
            <div class="kpi-info"><h3>Active & Ready</h3><p><?= $kpis['active'] ?></p></div>
            <i class="fa-solid fa-check-circle kpi-icon"></i>
        </div>
        <div class="kpi-card red">
            <div class="kpi-info"><h3>Disabled</h3><p><?= $kpis['inactive'] ?></p></div>
            <i class="fa-solid fa-ban kpi-icon"></i>
        </div>
    </div>

    <div class="table-card">
        <table>
            <thead>
                <tr>
                    <th style="width: 40px;">#</th>
                    <th>Formulation Profile</th>
                    <th>Short Name / Symbol</th>
                    <th>Clinical Description</th>
                    <th style="text-align:center;">Status</th>
                    <th style="text-align:right;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $sn = 1;
                foreach ($formulations as $f): 
                ?>
                <tr class="<?= $f['is_active'] == 0 ? 'inactive' : '' ?>">
                    <td style="font-weight:bold; color:#64748b;"><?= $sn++ ?></td>
                    <td style="font-weight:700; color:#0f172a; font-size:15px;">
                        <i class="fa-solid fa-flask" style="color:#64748b; margin-right:8px;"></i> <?= htmlspecialchars($f['formulation_name']) ?>
                    </td>
                    <td>
                        <span class="badge bg-blue" style="font-size:12px; font-family:monospace;"><?= htmlspecialchars($f['formulation_symbol'] ?: 'N/A') ?></span>
                    </td>
                    <td style="color:#475569;"><?= htmlspecialchars($f['description'] ?: '--') ?></td>
                    <td style="text-align:center;">
                        <?php if($f['is_active'] == 1): ?>
                            <span class="badge bg-green"><i class="fa-solid fa-check"></i> Active</span>
                        <?php else: ?>
                            <span class="badge bg-red"><i class="fa-solid fa-xmark"></i> Disabled</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="action-group">
                            <button class="btn-action btn-edit" title="Edit Formulation" onclick="openModal('edit', <?= $f['id'] ?>, '<?= htmlspecialchars(addslashes($f['formulation_name'])) ?>', '<?= htmlspecialchars(addslashes($f['formulation_symbol'] ?? '')) ?>', '<?= htmlspecialchars(addslashes($f['description'])) ?>', <?= $f['is_active'] ?>)">
                                <i class="fa-solid fa-pen-to-square"></i>
                            </button>
                            <button class="btn-action btn-toggle" title="<?= $f['is_active'] ? 'Deactivate' : 'Activate' ?>" onclick="toggleStatus(<?= $f['id'] ?>, <?= $f['is_active'] ?>)">
                                <i class="fa-solid <?= $f['is_active'] ? 'fa-toggle-on' : 'fa-toggle-off' ?>"></i>
                            </button>
                            <button class="btn-action btn-delete" title="Delete Formally" onclick="confirmDelete(<?= $f['id'] ?>, '<?= htmlspecialchars(addslashes($f['formulation_name'])) ?>')">
                                <i class="fa-solid fa-trash-can"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

</div>

<div class="modal-overlay" id="formModal">
    <div class="modal-card">
        <div class="modal-header">
            <h2 id="modalTitle">Add Formulation</h2>
            <button class="close-modal" type="button" onclick="closeModal()"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="">
            <div class="modal-body">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="formId" value="">
                
                <div style="display:grid; grid-template-columns: 2fr 1fr; gap:15px;">
                    <div class="form-group">
                        <label>Full Formulation Name</label>
                        <input type="text" name="formulation_name" id="formName" class="form-control" placeholder="e.g. Tablet, Syrup" required>
                    </div>
                    <div class="form-group">
                        <label>Symbol / Short Name</label>
                        <input type="text" name="formulation_symbol" id="formSymbol" class="form-control" placeholder="e.g. Tab, Syr">
                    </div>
                </div>
                
                <div class="form-group">
                    <label>Clinical Description</label>
                    <textarea name="description" id="formDesc" class="form-control" rows="3" placeholder="Brief description of the formulation..."></textarea>
                </div>

                <div class="form-group" style="margin-top:10px;">
                    <label class="toggle-switch">
                        <input type="checkbox" name="is_active" id="formActive" value="1" checked>
                        Active & Available in Pharmacy
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-cancel" onclick="closeModal()">Cancel</button>
                <button type="submit" class="btn-save"><i class="fa-solid fa-save"></i> Save Formulation</button>
            </div>
        </form>
    </div>
</div>

<script>
function openModal(action, id = '', name = '', symbol = '', desc = '', isActive = 1) {
    document.getElementById('formAction').value = action;
    document.getElementById('formId').value = id;
    document.getElementById('formName').value = name;
    document.getElementById('formSymbol').value = symbol;
    document.getElementById('formDesc').value = desc;
    document.getElementById('formActive').checked = (isActive == 1);
    
    document.getElementById('modalTitle').innerHTML = action === 'add' ? '<i class="fa-solid fa-plus"></i> Add New Formulation' : '<i class="fa-solid fa-pen-to-square"></i> Edit Formulation';
    
    document.getElementById('formModal').classList.add('active');
}

function closeModal() {
    document.getElementById('formModal').classList.remove('active');
}

function toggleStatus(id, currentStatus) {
    const actionText = currentStatus === 1 ? 'deactivate' : 'activate';
    if (confirm(`Are you sure you want to ${actionText} this formulation?`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = '';
        
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'action';
        actionInput.value = 'toggle';
        
        const idInput = document.createElement('input');
        idInput.type = 'hidden';
        idInput.name = 'id';
        idInput.value = id;
        
        const statusInput = document.createElement('input');
        statusInput.type = 'hidden';
        statusInput.name = 'current_status';
        statusInput.value = currentStatus;
        
        form.appendChild(actionInput);
        form.appendChild(idInput);
        form.appendChild(statusInput);
        document.body.appendChild(form);
        form.submit();
    }
}

function confirmDelete(id, name) {
    if (confirm(`WARNING: Are you sure you want to permanently delete '${name}'? \n\nIf this formulation is actively assigned to medicines in the catalog, deletion will be blocked.`)) {
        window.location.href = `deleteDrugFormulation.php?id=${id}`;
    }
}
</script>

</body>
</html>