<?php
session_start();
include 'db_config.php';

// --- SECURITY CHECK ---
if (!isset($_SESSION['user']) || ($_SESSION['role'] ?? 'user') !== 'central_admin') { 
    die("Access Denied. Only Central Administrators can manage system settings. <a href='inventory.php'>Back</a>"); 
}

$message = "";
$isSystemLocked = isSystemLocked(); 

// Fetch current announcement settings
$announcement = getSystemAnnouncement();

// --- HANDLE ACTIONS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // ACTION: TOGGLE SYSTEM LOCKDOWN
    if (isset($_POST['action']) && $_POST['action'] === 'toggle_maintenance') {
        $newStatus = $_POST['maintenance_status'];
        db_query("UPDATE ipgmm_system_settings SET setting_value = ? WHERE setting_key = 'maintenance_mode'", 's', [$newStatus]);
        $isSystemLocked = ($newStatus === '1');
        $message = "System status updated.";
    }

    // ACTION: SAVE ANNOUNCEMENT
    if (isset($_POST['action']) && $_POST['action'] === 'save_announcement') {
        $msg = trim($_POST['ann_msg']);
        $type = $_POST['ann_type'];
        $active = isset($_POST['ann_active']) ? '1' : '0';
        
        // Update all 3 keys using separate queries
        db_query("INSERT INTO ipgmm_system_settings (setting_key, setting_value) VALUES ('announcement_msg', ?) ON DUPLICATE KEY UPDATE setting_value = ?", 'ss', [$msg, $msg]);
        db_query("INSERT INTO ipgmm_system_settings (setting_key, setting_value) VALUES ('announcement_type', ?) ON DUPLICATE KEY UPDATE setting_value = ?", 'ss', [$type, $type]);
        db_query("INSERT INTO ipgmm_system_settings (setting_key, setting_value) VALUES ('announcement_active', ?) ON DUPLICATE KEY UPDATE setting_value = ?", 'ss', [$active, $active]);
        
        $message = "Announcement updated.";
        $announcement = getSystemAnnouncement(); // Refresh
    }

    // ACTION: SAVE DEPARTMENT
    if (isset($_POST['action']) && $_POST['action'] === 'save_dept') {
        $deptName = trim($_POST['dept_name']);
        $deptDesc = trim($_POST['dept_desc']);
        
        if (empty($deptName)) {
            $message = "Error: Department Name cannot be empty.";
        } else {
            $checkResult = db_query("SELECT department_name FROM ipgmm_departments WHERE department_name = ?", 's', [$deptName]);
            if ($checkResult && $checkResult->num_rows > 0) {
                db_query("UPDATE ipgmm_departments SET description = ? WHERE department_name = ?", 'ss', [$deptDesc, $deptName]);
                $message = "Department '$deptName' updated.";
            } else {
                db_query("INSERT INTO ipgmm_departments (department_name, description) VALUES (?, ?)", 'ss', [$deptName, $deptDesc]);
                $message = "New Department '$deptName' created.";
            }
        }
    }

    // ACTION: DELETE DEPARTMENT
    if (isset($_POST['action']) && $_POST['action'] === 'delete_dept') {
        $deptName = $_POST['dept_name'];
        try {
            db_query("DELETE FROM ipgmm_departments WHERE department_name = ?", 's', [$deptName]);
            $message = "Department '$deptName' deleted successfully.";
        } catch (Exception $e) {
            $message = "Error: Cannot delete department. It is likely linked to existing Users or Parts.";
        }
    }
}

// --- FETCH DATA ---
$departments = [];
$deptResult = db_query("SELECT department_name, description FROM ipgmm_departments ORDER BY department_name ASC");
if ($deptResult) { while ($row = $deptResult->fetch_assoc()) $departments[] = $row; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>System & Dept Master - IPG-SCM</title>
    <style>
        body { font-family: sans-serif; background: #f8fafc; padding: 20px; }
        .container { max-width: 900px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; border: 1px solid #ddd; }
        .nav { margin-bottom: 20px; border-bottom: 1px solid #eee; padding-bottom: 10px; }
        a { text-decoration: none; color: #2563eb; font-weight: bold; }
        
        .card { padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px; margin-bottom: 20px; background: #f1f5f9; }
        .card h3 { margin-top: 0; }
        
        .alert { padding: 10px; margin-bottom: 15px; border-radius: 4px; background: #dcfce7; color: #16a34a; }
        
        /* Lockdown Switch Styles */
        .lockdown-container { display: flex; align-items: center; justify-content: space-between; background: #fff3cd; border: 1px solid #ffeeba; padding: 15px; border-radius: 8px; color: #856404; }
        .lock-status { font-weight: bold; font-size: 1.2rem; }
        .btn-lock { padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-weight: bold; color: white; }
        .btn-lock.on { background: #dc2626; }
        .btn-lock.off { background: #16a34a; }

        input, button, select, textarea { padding: 8px; border-radius: 4px; border: 1px solid #ccc; box-sizing: border-box;}
        button.delete { background: #dc2626; color: white; border: none; cursor: pointer; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { padding: 10px; text-align: left; border-bottom: 1px solid #eee; background: white; }
    </style>
</head>
<body>
    <div class="container">
        <div class="nav"><a href="inventory.php">← Back to IPG-SCM Dashboard</a></div>

        <h1>⚙️ System & Department Master</h1>
        
        <?php if ($message): ?><div class="alert"><?php echo htmlspecialchars($message); ?></div><?php endif; ?>

        <!-- 1. SYSTEM LOCKDOWN CONTROL -->
        <div class="card" style="background: #fff; border-color: #f59e0b;">
            <h3 style="color: #d97706;">🚨 System Maintenance Mode</h3>
            <div class="lockdown-container">
                <div>
                    Status: <span class="lock-status" style="color: <?php echo $isSystemLocked ? '#dc2626' : '#16a34a'; ?>">
                        <?php echo $isSystemLocked ? "LOCKED" : "ACTIVE"; ?>
                    </span><br>
                    <small><?php echo $isSystemLocked ? "Only Central Admins can log in." : "All users have access."; ?></small>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="toggle_maintenance">
                    <?php if ($isSystemLocked): ?>
                        <input type="hidden" name="maintenance_status" value="0">
                        <button type="submit" class="btn-lock off">UNLOCK SYSTEM</button>
                    <?php else: ?>
                        <input type="hidden" name="maintenance_status" value="1">
                        <button type="submit" class="btn-lock on" onclick="return confirm('Are you sure? This will block all non-admin users.')">LOCK SYSTEM</button>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <!-- 2. SYSTEM ANNOUNCEMENT (NEW) -->
        <div class="card" style="background: #fff; border-color: #3b82f6;">
            <h3 style="color: #2563eb;">📢 System Announcement</h3>
            <form method="POST">
                <input type="hidden" name="action" value="save_announcement">
                <div style="margin-bottom: 10px;">
                    <textarea name="ann_msg" rows="3" style="width: 100%;" placeholder="Enter message to display on login page..."><?php echo htmlspecialchars($announcement['msg']); ?></textarea>
                </div>
                <div style="display: flex; gap: 10px; align-items: center;">
                    <select name="ann_type">
                        <option value="info" <?php echo $announcement['type']=='info'?'selected':''; ?>>ℹ️ Info (Blue)</option>
                        <option value="warning" <?php echo $announcement['type']=='warning'?'selected':''; ?>>⚠️ Warning (Yellow)</option>
                        <option value="danger" <?php echo $announcement['type']=='danger'?'selected':''; ?>>🚨 Urgent (Red)</option>
                    </select>
                    
                    <label style="font-weight: bold;">
                        <input type="checkbox" name="ann_active" <?php echo $announcement['active']?'checked':''; ?>> Show on Login Page
                    </label>
                    
                    <button type="submit" style="background: #2563eb; color: white; border: none; cursor: pointer;">Update Message</button>
                </div>
            </form>
        </div>

        <!-- 3. DEPARTMENT MASTER -->
        <div class="card">
            <h3>Create or Update Department</h3>
            <form method="POST">
                <input type="hidden" name="action" value="save_dept">
                <div style="display: flex; gap: 10px;">
                    <input type="text" name="dept_name" placeholder="Dept Name (e.g. Fabrication)" required style="flex: 1;">
                    <input type="text" name="dept_desc" placeholder="Description" style="flex: 2;">
                    <button type="submit" style="background: #2563eb; color: white; border: none; cursor: pointer; font-weight: bold;">Save</button>
                </div>
            </form>

            <table style="width:100%; margin-top:15px;">
                <thead><tr><th>Department Name</th><th>Description</th><th>Action</th></tr></thead>
                <tbody>
                    <?php foreach ($departments as $dept): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($dept['department_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($dept['description']); ?></td>
                            <td>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Delete department? Check if linked to users/parts first.')">
                                    <input type="hidden" name="action" value="delete_dept">
                                    <input type="hidden" name="dept_name" value="<?php echo htmlspecialchars($dept['department_name']); ?>">
                                    <button type="submit" class="delete">Delete</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>