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

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

$message = '';

// ==============================================================================
// 1. HANDLE POST ACTIONS (Add, Edit, Toggle, Delete)
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $location_name = trim($_POST['location_name']);
        $location_type = trim($_POST['location_type']);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        $stmt = $conn->prepare("INSERT INTO inventory_locations (location_name, location_type, is_active) VALUES (?, ?, ?)");
        $stmt->bind_param("ssi", $location_name, $location_type, $is_active);
        if ($stmt->execute()) {
            $message = "<div class='alert alert-success'><i class='fa-solid fa-check-circle'></i> Location '$location_name' added successfully!</div>";
        } else {
            $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> Error: Could not add location. It might already exist.</div>";
        }
        $stmt->close();
        
    } elseif ($action === 'edit') {
        $id = (int)$_POST['id'];
        $location_name = trim($_POST['location_name']);
        $location_type = trim($_POST['location_type']);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        $stmt = $conn->prepare("UPDATE inventory_locations SET location_name = ?, location_type = ?, is_active = ? WHERE id = ?");
        $stmt->bind_param("ssii", $location_name, $location_type, $is_active, $id);
        if ($stmt->execute()) {
            $message = "<div class='alert alert-success'><i class='fa-solid fa-check-circle'></i> Location updated successfully!</div>";
        } else {
            $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> Error updating location.</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 inventory_locations 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> Location status updated successfully.</div>";
        }
        $stmt->close();
        
    } elseif ($action === 'delete') {
        $id = (int)$_POST['id'];
        
        // ENTERPRISE SAFETY: Check if this location has active stock before deleting
        $check_stmt = $conn->prepare("SELECT COUNT(*) as stock_count FROM inventory_stock WHERE location_id = ?");
        $check_stmt->bind_param("i", $id);
        $check_stmt->execute();
        $stock_count = $check_stmt->get_result()->fetch_assoc()['stock_count'];
        $check_stmt->close();
        
        if ($stock_count > 0) {
            $message = "<div class='alert alert-danger'><i class='fa-solid fa-ban'></i> <strong>Deletion Blocked:</strong> This location currently holds {$stock_count} item records in its inventory. Transfer the stock out or Deactivate the location instead.</div>";
        } else {
            $del_stmt = $conn->prepare("DELETE FROM inventory_locations WHERE id = ?");
            $del_stmt->bind_param("i", $id);
            if ($del_stmt->execute()) {
                $message = "<div class='alert alert-success'><i class='fa-solid fa-trash-can'></i> Location permanently deleted.</div>";
            } else {
                $message = "<div class='alert alert-danger'><i class='fa-solid fa-triangle-exclamation'></i> Error deleting location.</div>";
            }
            $del_stmt->close();
        }
    }
}

// ==============================================================================
// 2. DYNAMIC SQL SEARCH & FILTER
// ==============================================================================
$search_text = $_GET['search'] ?? '';
$filter_type = $_GET['location_type'] ?? '';

$query = "SELECT * FROM inventory_locations WHERE 1=1 ";
$params = [];
$types = "";

if ($filter_type !== '') {
    $query .= " AND location_type = ? ";
    $params[] = $filter_type;
    $types .= "s";
}
if ($search_text !== '') {
    $query .= " AND location_name LIKE ? ";
    $search_param = "%{$search_text}%";
    $params[] = $search_param;
    $types .= "s";
}

$query .= " ORDER BY location_type DESC, location_name ASC";

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$locations = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// ==============================================================================
// 3. KPI CALCULATIONS
// ==============================================================================
$kpis = ['total' => count($locations), 'stores' => 0, 'dispensaries' => 0, 'inactive' => 0];
foreach ($locations as $loc) {
    if ($loc['location_type'] == 'Store') $kpis['stores']++;
    if ($loc['location_type'] == 'Dispensary') $kpis['dispensaries']++;
    if ($loc['is_active'] == 0) $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 Stores & Dispensaries | 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: #4f46e5; margin: 0; font-size: 24px; font-weight: 800; text-transform: uppercase; display:flex; align-items:center; gap:10px; }
    .btn-add { background: #4f46e5; color: #fff; padding: 12px 20px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; box-shadow: 0 4px 6px rgba(79, 70, 229, 0.2); transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; }
    .btn-add:hover { background: #3730a3; 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(4, 1fr); gap: 15px; margin-bottom: 25px; }
    .kpi-card { background: #fff; padding: 20px; border-radius: 12px; border: 1px solid var(--border); border-left: 5px solid #4f46e5; 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.blue { border-left-color: #0ea5e9; }
    .kpi-card.red { border-left-color: #dc2626; background: #fef2f2; }
    .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; }
    .kpi-card.red .kpi-icon { color: #fca5a5; }

    .filter-panel { background: #fff; padding: 20px; border-radius: 12px; margin-bottom: 25px; border: 1px solid var(--border); box-shadow: 0 4px 10px rgba(0,0,0,0.02); }
    .filter-grid { display: grid; grid-template-columns: 2fr 1fr auto; gap: 15px; align-items: end; }
    .filter-group { display: flex; flex-direction: column; gap: 6px; }
    .filter-group label { font-size: 12px; font-weight: 700; color: #64748b; text-transform: uppercase; }
    .filter-control { padding: 11px 12px; border-radius: 6px; border: 1px solid #cbd5e1; outline: none; font-size: 14px; background: #fff; }
    .filter-control:focus { border-color: #4f46e5; box-shadow: 0 0 0 3px #e0e7ff; }
    .btn-filter { background: #4f46e5; color: #fff; border: none; padding: 12px 25px; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.2s; height: 42px; }

    .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-green { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
    .bg-blue { background: #e0f2fe; color: #0369a1; border: 1px solid #bae6fd; }
    .bg-indigo { background: #e0e7ff; color: #3730a3; border: 1px solid #c7d2fe; }
    .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: 450px; 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: #4f46e5; 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: #4f46e5; box-shadow: 0 0 0 3px #e0e7ff; }
    
    .toggle-switch { display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 700; color: #0f172a; font-size: 14px; margin-top: 10px; }
    .toggle-switch input { width: 18px; height: 18px; accent-color: #4f46e5; 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: #4f46e5; color: #fff; padding: 10px 20px; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; transition: 0.2s; }
    .btn-save:hover { background: #3730a3; }
    .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="manageProducts.php" style="color:#64748b; text-decoration:none; font-weight:700; font-size:13px;"><i class="fa-solid fa-arrow-left"></i> Back to Inventory Dashboard</a>
    </div>

    <div class="header-bar">
        <h2><i class="fa-solid fa-shop"></i> Manage Stores & Dispensaries</h2>
        <button class="btn-add" onclick="openModal('add')"><i class="fa-solid fa-plus"></i> Add New Location</button>
    </div>

    <?= $message ?>

    <div class="kpi-grid">
        <div class="kpi-card">
            <div class="kpi-info"><h3>Total Locations</h3><p><?= $kpis['total'] ?></p></div>
            <i class="fa-solid fa-building kpi-icon"></i>
        </div>
        <div class="kpi-card blue">
            <div class="kpi-info"><h3>Main Bulk Stores</h3><p><?= $kpis['stores'] ?></p></div>
            <i class="fa-solid fa-boxes-stacked kpi-icon"></i>
        </div>
        <div class="kpi-card green">
            <div class="kpi-info"><h3>Dispensaries (POS)</h3><p><?= $kpis['dispensaries'] ?></p></div>
            <i class="fa-solid fa-hand-holding-medical kpi-icon"></i>
        </div>
        <div class="kpi-card red">
            <div class="kpi-info"><h3 style="color:#b91c1c;">Inactive Locations</h3><p style="color:#b91c1c;"><?= $kpis['inactive'] ?></p></div>
            <i class="fa-solid fa-store-slash kpi-icon"></i>
        </div>
    </div>

    <div class="filter-panel">
        <form method="GET" action="">
            <div class="filter-grid">
                <div class="filter-group">
                    <label>Search Location Name</label>
                    <input type="text" name="search" class="filter-control" placeholder="e.g. OPD Dispensary" value="<?= htmlspecialchars($search_text) ?>">
                </div>
                <div class="filter-group">
                    <label>Location Type</label>
                    <select name="location_type" class="filter-control">
                        <option value="">All Types</option>
                        <option value="Store" <?= $filter_type == 'Store' ? 'selected' : '' ?>>Main Stores</option>
                        <option value="Dispensary" <?= $filter_type == 'Dispensary' ? 'selected' : '' ?>>Dispensaries</option>
                    </select>
                </div>
                <div>
                    <button type="submit" class="btn-filter"><i class="fa-solid fa-filter"></i> Filter Results</button>
                    <?php if($search_text || $filter_type): ?>
                        <a href="storesAndDispensary.php" style="display:block; text-align:center; margin-top:8px; font-size:12px; color:#dc2626; text-decoration:none; font-weight:700;">Reset Filters</a>
                    <?php endif; ?>
                </div>
            </div>
        </form>
    </div>

    <div class="table-card">
        <table>
            <thead>
                <tr>
                    <th style="width: 40px;">#</th>
                    <th>Location Name</th>
                    <th>Location Type</th>
                    <th style="text-align:center;">Status</th>
                    <th style="text-align:right;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if(empty($locations)): ?>
                    <tr><td colspan="5" style="text-align:center; padding:30px; color:#94a3b8;">No locations found matching your criteria.</td></tr>
                <?php else:
                    $sn = 1;
                    foreach ($locations as $loc): ?>
                <tr class="<?= $loc['is_active'] == 0 ? 'inactive' : '' ?>">
                    <td style="font-weight:bold; color:#64748b;"><?= $sn++ ?></td>
                    <td style="font-weight:700; color:#0f172a; font-size:15px;">
                        <?= htmlspecialchars($loc['location_name']) ?>
                    </td>
                    <td>
                        <?php if($loc['location_type'] == 'Store'): ?>
                            <span class="badge bg-indigo"><i class="fa-solid fa-boxes-stacked"></i> Main Store</span>
                        <?php else: ?>
                            <span class="badge bg-blue"><i class="fa-solid fa-hand-holding-medical"></i> Dispensary</span>
                        <?php endif; ?>
                    </td>
                    <td style="text-align:center;">
                        <?php if($loc['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 Location" onclick="openModal('edit', <?= $loc['id'] ?>, '<?= htmlspecialchars(addslashes($loc['location_name'])) ?>', '<?= htmlspecialchars($loc['location_type']) ?>', <?= $loc['is_active'] ?>)">
                                <i class="fa-solid fa-pen-to-square"></i>
                            </button>
                            <button class="btn-action btn-toggle" title="<?= $loc['is_active'] ? 'Deactivate' : 'Activate' ?>" onclick="toggleStatus(<?= $loc['id'] ?>, <?= $loc['is_active'] ?>)">
                                <i class="fa-solid <?= $loc['is_active'] ? 'fa-toggle-on' : 'fa-toggle-off' ?>"></i>
                            </button>
                            <button class="btn-action btn-delete" title="Delete Formally" onclick="confirmDelete(<?= $loc['id'] ?>, '<?= htmlspecialchars(addslashes($loc['location_name'])) ?>')">
                                <i class="fa-solid fa-trash-can"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

</div>

<div class="modal-overlay" id="locationModal">
    <div class="modal-card">
        <div class="modal-header">
            <h2 id="modalTitle">Add Location</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 class="form-group">
                    <label>Location Name</label>
                    <input type="text" name="location_name" id="formName" class="form-control" placeholder="e.g. Ward 3 Dispensary" required>
                </div>
                
                <div class="form-group">
                    <label>Location Type</label>
                    <select name="location_type" id="formType" class="form-control" required>
                        <option value="Dispensary">Dispensary (Issues to Patients)</option>
                        <option value="Store">Main Store (Receives Bulk Purchases)</option>
                    </select>
                </div>

                <label class="toggle-switch">
                    <input type="checkbox" name="is_active" id="formActive" value="1" checked>
                    Location is Active & Operational
                </label>
            </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 Location</button>
            </div>
        </form>
    </div>
</div>

<form id="actionForm" method="POST" style="display:none;">
    <input type="hidden" name="action" id="actAction">
    <input type="hidden" name="id" id="actId">
    <input type="hidden" name="current_status" id="actStatus">
</form>

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

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

function toggleStatus(id, currentStatus) {
    const actionText = currentStatus === 1 ? 'deactivate' : 'activate';
    if (confirm(`Are you sure you want to ${actionText} this location?`)) {
        document.getElementById('actAction').value = 'toggle';
        document.getElementById('actId').value = id;
        document.getElementById('actStatus').value = currentStatus;
        document.getElementById('actionForm').submit();
    }
}

function confirmDelete(id, name) {
    if (confirm(`DANGER: Are you sure you want to permanently delete '${name}'?\n\nIf there is ANY stock currently sitting in this location, the system will block the deletion to protect inventory records.`)) {
        document.getElementById('actAction').value = 'delete';
        document.getElementById('actId').value = id;
        document.getElementById('actionForm').submit();
    }
}
</script>

</body>
</html>