<?php 
include 'header.php'; 

// --- ১. অফিসার তৈরি করা (পারমিশন সহ) ---
if(isset($_POST['add_officer'])) {
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $plain_pass = $_POST['password']; 
    $hashed_pass = password_hash($plain_pass, PASSWORD_DEFAULT); 
    
    $chk = $conn->query("SELECT * FROM officer_users WHERE email='$email'");
    if($chk->num_rows == 0) {
        $conn->query("INSERT INTO officer_users (email, password, plain_password) VALUES ('$email', '$hashed_pass', '$plain_pass')");
        $new_off_id = $conn->insert_id;

        // পারমিশন সেভ করা
        if(isset($_POST['cat_perms']) && is_array($_POST['cat_perms'])) {
            foreach($_POST['cat_perms'] as $cat_id) {
                $cat_id = (int)$cat_id;
                $conn->query("INSERT INTO officer_permissions (officer_id, category_id) VALUES ($new_off_id, $cat_id)");
            }
        }
        echo "<script>alert('Officer Created with Permissions!'); window.location.href='officers.php';</script>";
    } else {
        echo "<script>alert('Email already exists!');</script>";
    }
}

// --- ২. অফিসার আপডেট (এডিট) করা ---
if(isset($_POST['update_officer'])) {
    $id = (int)$_POST['off_id'];
    $email = mysqli_real_escape_string($conn, $_POST['off_email']);
    $plain_pass = $_POST['off_password'];
    $hashed_pass = password_hash($plain_pass, PASSWORD_DEFAULT);

    $conn->query("UPDATE officer_users SET email='$email', password='$hashed_pass', plain_password='$plain_pass' WHERE id=$id");
    
    // পুরাতন পারমিশন মুছে নতুনগুলো এড করা
    $conn->query("DELETE FROM officer_permissions WHERE officer_id=$id");
    if(isset($_POST['cat_perms']) && is_array($_POST['cat_perms'])) {
        foreach($_POST['cat_perms'] as $cat_id) {
            $cat_id = (int)$cat_id;
            $conn->query("INSERT INTO officer_permissions (officer_id, category_id) VALUES ($id, $cat_id)");
        }
    }
    echo "<script>alert('Officer Updated!'); window.location.href='officers.php';</script>";
}

// --- ৩. অফিসার ডিলিট করা ---
if(isset($_GET['del_id'])) {
    $id = (int)$_GET['del_id'];
    $conn->query("DELETE FROM officer_users WHERE id=$id");
    $conn->query("DELETE FROM officer_permissions WHERE officer_id=$id");
    header("Location: officers.php");
}
?>

<!-- অফিসার বাটন কন্ট্রোল (Toggle Switch) -->
<div class="control-box">
    <h4 style="color:var(--accent); margin-top:0;"><i class="fas fa-power-off"></i> OFFICER AREA CONTROL</h4>
    <form action="../settings_process.php" method="POST">
        <div class="switch-container">
            <span class="switch-label">Home Page Officer Button</span>
            <div style="display: flex; align-items: center;">
                <label class="switch">
                    <!-- যদি ১ থাকে তবে checked হবে -->
                    <input type="hidden" name="show_officer_btn" value="0">
                    <input type="checkbox" name="show_officer_btn" value="1" <?= ($theme['show_officer_btn'] == 1) ? 'checked' : '' ?>>
                    <span class="slider"></span>
                    <span class="status-on">ON</span>
                    <span class="status-off">OFF</span>
                </label>
            </div>
        </div>
        <button class="btn" name="update_settings" style="margin-top: 15px;">UPDATE SYSTEM</button>
    </form>
</div>

<div class="control-box">
    <h4 style="color:var(--accent); margin-top:0;"><i class="fas fa-user-shield"></i> ADD NEW OFFICER</h4>
    <form action="" method="POST">
        <label>Officer Email</label>
        <input type="email" name="email" placeholder="email@example.com" required>
        <label>Set Password</label>
        <input type="text" name="password" placeholder="Enter Password" required>
        
        <label style="margin-top:20px;">ASSIGN CATEGORIES (PERMISSIONS)</label>
        <div style="display:grid; grid-template-columns: 1fr 1fr; gap:10px; background:#000; padding:15px; border-radius:5px; margin-top:5px; border:1px solid #333;">
            <?php 
            $cats = $conn->query("SELECT id, name FROM categories ORDER BY name ASC");
            while($ct = $cats->fetch_assoc()){
                echo '<label style="color:#eee; font-size:12px; margin:0; display:flex; align-items:center; cursor:pointer;">
                        <input type="checkbox" name="cat_perms[]" value="'.$ct['id'].'" style="width:auto; margin-right:8px;"> '.$ct['name'].'
                      </label>';
            }
            ?>
        </div>
        
        <button class="btn" name="add_officer">CREATE OFFICER ACCOUNT</button>
    </form>
</div>

<h4 style="color:#fff; margin:25px 0 10px;"><i class="fas fa-users"></i> ACTIVE OFFICERS</h4>
<ul style="padding:0; list-style:none;">
    <?php
    $res = $conn->query("SELECT * FROM officer_users ORDER BY id DESC");
    while($r = $res->fetch_assoc()) {
        $off_id = $r['id'];
        // এই অফিসারের পারমিশন নেওয়া
        $p_res = $conn->query("SELECT category_id FROM officer_permissions WHERE officer_id=$off_id");
        $p_ids = []; while($p = $p_res->fetch_assoc()) $p_ids[] = $p['category_id'];
        $p_json = json_encode($p_ids);

        echo '<li class="list-item" style="flex-wrap: wrap; gap: 10px;">
            <div style="flex:1;">
                <span><i class="fas fa-user" style="color:var(--accent);"></i> '.$r['email'].'</span><br>
                <small style="color:#aaa;">Pass: '.$r['plain_password'].' | Allowed: '.count($p_ids).' Categories</small>
            </div>
            <div style="display: flex; gap: 10px; align-items: center;">
                <button onclick="copyOfficerInfo(\''.$r['email'].'\', \''.$r['plain_password'].'\', this)" style="background: rgba(0,242,255,0.1); border: 1px solid var(--accent); color: var(--accent); padding: 5px 10px; cursor: pointer; border-radius: 4px; font-size: 11px;">Copy</button>
                <a href="#" onclick=\'editOfficer('.$r['id'].', "'.$r['email'].'", "'.$r['plain_password'].'", '.$p_json.')\' style="color:var(--accent); text-decoration:none;"><i class="fas fa-edit"></i></a>
                <a href="?del_id='.$r['id'].'" onclick="return confirm(\'Remove?\')" style="color:red; text-decoration:none;"><i class="fas fa-trash"></i></a>
            </div>
        </li>';
    }
    ?>
</ul>

<!-- EDIT MODAL -->
<div id="editOfficerModal" class="modal">
    <div class="modal-content" style="max-width:450px;">
        <h3 style="color:var(--accent); margin-top:0;">EDIT OFFICER</h3>
        <form action="" method="POST">
            <input type="hidden" name="off_id" id="edit_off_id">
            <label>Email</label><input type="email" name="off_email" id="edit_off_email" required>
            <label>Password</label><input type="text" name="off_password" id="edit_off_password" required>
            
            <label style="margin-top:15px;">UPDATE PERMISSIONS</label>
            <div id="edit_perms_box" style="display:grid; grid-template-columns: 1fr 1fr; gap:10px; background:#000; padding:15px; border-radius:5px; border:1px solid #444; max-height:150px; overflow-y:auto;">
                <?php 
                $cats->data_seek(0);
                while($ct = $cats->fetch_assoc()){
                    echo '<label style="color:#eee; font-size:12px; margin:0; display:flex; align-items:center;">
                            <input type="checkbox" name="cat_perms[]" value="'.$ct['id'].'" class="edit-perm-check"> '.$ct['name'].'
                          </label>';
                }
                ?>
            </div>
            <button class="btn" name="update_officer">UPDATE OFFICER</button>
        </form>
        <button onclick="$('#editOfficerModal').fadeOut()" class="btn" style="background:#333; margin-top:10px;">CANCEL</button>
    </div>
</div>

<style>
    /* Toggle Switch ডিজাইন */
    .switch-container { display: flex; align-items: center; justify-content: space-between; background: rgba(0,0,0,0.3); padding: 15px; border-radius: 8px; border: 1px solid #333; margin-top: 10px; }
    .switch-label { font-size: 13px; font-weight: bold; color: #eee; }
    
    .switch { position: relative; display: inline-block; width: 60px; height: 28px; }
    .switch input { opacity: 0; width: 0; height: 0; }
    .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ff3333; transition: .4s; border-radius: 34px; }
    .slider:before { position: absolute; content: ""; height: 20px; width: 20px; left: 4px; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%; }
    
    input:checked + .slider { background-color: #00ff00; }
    input:checked + .slider:before { transform: translateX(32px); }
    
    .status-on { color: #00ff00; display: none; font-weight: bold; margin-left: 10px; }
    .status-off { color: #ff3333; display: inline; font-weight: bold; margin-left: 10px; }
    input:checked ~ .status-on { display: inline; }
    input:checked ~ .status-off { display: none; }
</style>

<script>
function editOfficer(id, email, pass, perms) {
    $('#edit_off_id').val(id);
    $('#edit_off_email').val(email);
    $('#edit_off_password').val(pass);
    
    // সব চেকবক্স আনচেক করা
    $('.edit-perm-check').prop('checked', false);
    // অফিসারের পারমিশন অনুযায়ী চেক করা
    perms.forEach(function(pid) {
        $('.edit-perm-check[value="'+pid+'"]').prop('checked', true);
    });
    
    $('#editOfficerModal').fadeIn();
}

function copyOfficerInfo(email, pass, btn) {
    const textToCopy = "Email: " + email + "\nPassword: " + pass;
    navigator.clipboard.writeText(textToCopy).then(() => {
        const old = btn.innerText; btn.innerText = 'Copied!';
        setTimeout(() => { btn.innerText = old; }, 2000);
    });
}
</script>
<?php include 'footer.php'; ?>