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

// 1. Load Header (Includes DB Connection & Session Gatekeeper)
include_once('../includes/header.php'); 

// 2. Authorization Guard: Securely lock down this page for Super Admins only
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'Admin') {
    echo "<script>window.location.href='../login.php';</script>";
    exit;
}

$message = "";

// --- LOGIC: CREATE USER ACCOUNT ---
if (isset($_POST['create_user'])) {
    $name     = mysqli_real_escape_string($conn, $_POST['full_name']);
    $email    = mysqli_real_escape_string($conn, $_POST['email']);
    $phone    = mysqli_real_escape_string($conn, $_POST['phone']);
    $password = password_hash($_POST['password'], PASSWORD_BCRYPT); // Using standard secure BCrypt
    $role     = $_POST['role'];
    $team     = ($role == 'Scheduler' || $role == 'Admin') ? 'None' : $_POST['team'];

    try {
        $sql = "INSERT INTO users (full_name, email, phone, password, role, team) 
                VALUES ('$name', '$email', '$phone', '$password', '$role', '$team')";
        
        if (mysqli_query($conn, $sql)) {
            $message = "<div class='alert alert-success border-0 shadow-sm'>✅ Staff account created successfully for $name</div>";
        }
    } catch (mysqli_sql_exception $e) {
        if ($e->getCode() == 1062) {
            $message = "<div class='alert alert-warning border-0 shadow-sm'>
                            <strong>Registration Failed:</strong> The email <b>$email</b> is already registered.
                        </div>";
        } else {
            $message = "<div class='alert alert-danger border-0 shadow-sm'>Something went wrong. Please try again.</div>";
        }
    }
}

// --- LOGIC: ADD NEW PLATFORM INTEGRATION ---
if (isset($_POST['add_platform'])) {
    $plat_name = mysqli_real_escape_string($conn, trim($_POST['platform_name']));
    
    if (!empty($plat_name)) {
        try {
            $sql = "INSERT INTO platforms (name, status) VALUES ('$plat_name', 'Active')";
            if (mysqli_query($conn, $sql)) {
                $message = "<div class='alert alert-success border-0 shadow-sm'>✅ Dynamic platform <b>$plat_name</b> successfully registered!</div>";
            }
        } catch (mysqli_sql_exception $e) {
            if ($e->getCode() == 1062) {
                $message = "<div class='alert alert-warning border-0 shadow-sm'>⚠️ Platform <b>$plat_name</b> is already registered.</div>";
            } else {
                $message = "<div class='alert alert-danger border-0 shadow-sm'>Failed to integrate platform channel.</div>";
            }
        }
    }
}

// --- LOGIC: TOGGLE PLATFORM STATUS ---
if (isset($_GET['toggle_platform'])) {
    $p_id = (int)$_GET['toggle_platform'];
    $p_res = mysqli_query($conn, "SELECT status FROM platforms WHERE id = $p_id");
    if ($p_row = mysqli_fetch_assoc($p_res)) {
        $new_status = ($p_row['status'] === 'Active') ? 'Inactive' : 'Active';
        mysqli_query($conn, "UPDATE platforms SET status = '$new_status' WHERE id = $p_id");
        echo "<script>window.location.href='users.php';</script>";
        exit;
    }
}

// --- LOGIC: DELETE PLATFORM CHANNELS ---
if (isset($_GET['delete_platform'])) {
    $p_id = (int)$_GET['delete_platform'];
    mysqli_query($conn, "DELETE FROM platforms WHERE id = $p_id");
    echo "<script>window.location.href='users.php';</script>";
    exit;
}

// --- LOGIC: DELETE USER ACCOUNT ---
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    mysqli_query($conn, "DELETE FROM users WHERE id=$id");
    echo "<script>window.location.href='users.php';</script>";
    exit;
}
?>

<div class="row g-4 mb-5">
    <div class="col-12">
        <?php echo $message; ?>
    </div>

    <div class="col-lg-7">
        <div class="main-card shadow-sm border-0 h-100">
            <div class="card-header-dark p-4">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold text-white text-uppercase">Staff Management</h5>
                    
                </div>
            </div>

            <div class="p-4 bg-white rounded-bottom border border-top-0">
                <h6 class="section-title text-muted text-uppercase fw-bold small mb-3">1. Add New Staff Member</h6>
                <form action="users.php" method="POST" class="mb-5">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Full Name</label>
                            <input type="text" name="full_name" class="form-control form-control-sm" placeholder="Isuru Sahan" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Email Address</label>
                            <input type="email" name="email" class="form-control form-control-sm" placeholder="isuru@swarnavahini.lk" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Phone Number</label>
                            <input type="text" name="phone" class="form-control form-control-sm" placeholder="+94 7X XXX XXXX" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Login Password</label>
                            <input type="password" name="password" class="form-control form-control-sm" placeholder="••••••••••••" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Assign System Role</label>
                            <select name="role" id="roleSelect" class="form-select form-select-sm" onchange="checkRole()">
                                <option value="Editor">Editor</option>
                                <option value="Scheduler">Scheduler</option>
                                <option value="Admin">Admin</option>
                            </select>
                        </div>
                        <div class="col-md-6" id="teamSelection">
                            <label class="form-label small fw-bold">Assign Department Team</label>
                            <select name="team" class="form-select form-select-sm">
                                <option value="News Team">News Team</option>
                                <option value="Content Team">Content Team</option>
                            </select>
                        </div>
                        <div class="col-12 text-end mt-3">
                            <button type="submit" name="create_user" class="btn btn-primary btn-sm px-4 fw-bold rounded-pill shadow-sm">Create Account</button>
                        </div>
                    </div>
                </form>

                <h6 class="section-title text-muted text-uppercase fw-bold small mb-3">2. Registered Staff Members</h6>
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="bg-light">
                            <tr>
                                <th class="py-2 border-0 small fw-bold text-muted">NAME / CONTACT</th>
                                <th class="py-2 border-0 small fw-bold text-muted">ROLE</th>
                                <th class="py-2 border-0 small fw-bold text-muted">TEAM</th>
                                <th class="py-2 border-0 small fw-bold text-muted text-end">ACTIONS</th>
                            </tr>
                        </thead>
                        <tbody class="border-top-0">
                            <?php 
                            $res = mysqli_query($conn, "SELECT * FROM users ORDER BY id DESC");
                            while($row = mysqli_fetch_assoc($res)) {
                                if ($row['role'] == 'Admin') $roleClass = 'bg-danger text-white';
                                elseif ($row['role'] == 'Scheduler') $roleClass = 'badge-scheduler';
                                else $roleClass = 'badge-editor';
                                
                                $teamLabel = ($row['role'] == 'Scheduler' || $row['role'] == 'Admin') ? '<span class="text-muted opacity-50">—</span>' : htmlspecialchars($row['team']);
                            ?>
                            <tr>
                                <td class="py-3">
                                    <div class="fw-bold text-dark small mb-0"><?php echo htmlspecialchars($row['full_name']); ?></div>
                                    <small class="text-muted" style="font-size: 11px;"><?php echo htmlspecialchars($row['phone']); ?></small>
                                </td>
                                <td>
                                    <span class="badge badge-role <?php echo $roleClass; ?> uppercase shadow-sm" style="font-size: 9px;"><?php echo $row['role']; ?></span>
                                </td>
                                <td class="small text-secondary fw-bold"><?php echo $teamLabel; ?></td>
                                <td class="text-end">
                                    <a href="users.php?delete=<?php echo $row['id']; ?>" 
                                       class="btn btn-sm btn-outline-danger px-2 py-0 small rounded-pill" 
                                       onclick="return confirm('Permanently drop this user account profile?')">
                                        <i class="bi bi-trash3 shadow-none"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-5">
        <div class="main-card shadow-sm border-0 h-100">
            <div class="card-header-dark p-4">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold text-white text-uppercase">Platforms</h5>
                  
                </div>
            </div>

            <div class="p-4 bg-white rounded-bottom border border-top-0">
                <h6 class="section-title text-muted text-uppercase fw-bold small mb-3">1. Add Live Media Platform</h6>
                
                <form action="users.php" method="POST" class="mb-4">
                    <div class="input-group input-group-sm mb-3">
                        <input type="text" name="platform_name" class="form-control shadow-none" placeholder="E.g., Viber Channel, Threads" required autocomplete="off">
                        <button type="submit" name="add_platform" class="btn btn-success fw-bold px-3">Add Channel</button>
                    </div>
                </form>

                <h6 class="section-title text-muted text-uppercase fw-bold small mb-3">2. Active Distribution Channels</h6>
                <div class="list-group list-group-flush border rounded-3 overflow-hidden shadow-sm">
                    <?php 
                    // Verify if platforms table tracking infrastructure exists
                    $check_plat_table = mysqli_query($conn, "SHOW TABLES LIKE 'platforms'");
                    if(mysqli_num_rows($check_plat_table) > 0):
                        $plat_res = mysqli_query($conn, "SELECT * FROM platforms ORDER BY name ASC");
                        if(mysqli_num_rows($plat_res) > 0):
                            while($p_row = mysqli_fetch_assoc($plat_res)):
                                $statusBadge = ($p_row['status'] === 'Active') ? 'bg-success' : 'bg-secondary';
                        ?>
                        <div class="list-group-item d-flex justify-content-between align-items-center p-3">
                            <div>
                                <span class="fw-bold small text-dark"><i class="bi bi-layers-half text-primary me-2"></i><?php echo htmlspecialchars($p_row['name']); ?></span>
                                <a href="users.php?toggle_platform=<?php echo $p_row['id']; ?>" class="badge <?php echo $statusBadge; ?> text-white text-decoration-none ms-2 shadow-sm" style="font-size: 9px; cursor: pointer;" title="Toggle Channel Status">
                                    <?php echo strtoupper($p_row['status']); ?>
                                </a>
                            </div>
                            <a href="users.php?delete_platform=<?php echo $p_row['id']; ?>" class="text-danger opacity-75 hover-opacity-100 text-decoration-none small" onclick="return confirm('Delete this dynamic distribution platform channel?')">
                                <i class="bi bi-x-circle-fill"></i>
                            </a>
                        </div>
                        <?php 
                            endwhile;
                        else:
                            echo "<div class='p-4 text-center text-muted small italic bg-light'>No pipeline systems registered.</div>";
                        endif;
                    else:
                        echo "<div class='alert alert-danger m-3 small border-0'>System Error: The `platforms` base table structure has not yet been applied to phpMyAdmin.</div>";
                    endif;
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function checkRole() {
    const role = document.getElementById('roleSelect').value;
    const teamBox = document.getElementById('teamSelection');
    if(role === 'Scheduler' || role === 'Admin') {
        teamBox.style.opacity = "0.3";
        teamBox.style.pointerEvents = "none";
    } else {
        teamBox.style.opacity = "1";
        teamBox.style.pointerEvents = "auto";
    }
}
// Run checking procedure instantly on script resolution load
checkRole();
</script>

<?php include_once('../includes/footer.php'); ?>