<?php
require_once __DIR__ . '/../library/auth.php';
allow_roles(['admin']);

$action = $_GET['action'] ?? '';

// session se school_id le
$school_id = $_SESSION['school_id'] ?? 0; // super_admin = 0

if ($action == 'save' && $_SERVER['REQUEST_METHOD'] == 'POST') {

    $id = $_POST['id'] ?? '';
    $name = $_POST['name'];
    $username = $_POST['username'];
    $role = $_POST['role'];

    // password hash
    if (!empty($_POST['password'])) {
        $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
    }

    // ================= UPDATE =================
    if ($id) {

        if (!empty($_POST['password'])) {

            if ($school_id == 0) {
                $stmt = $pdo->prepare("UPDATE users SET name=?, username=?, role=?, password=? WHERE id=?");
                $stmt->execute([$name, $username, $role, $pass, $id]);
            } else {
                $stmt = $pdo->prepare("UPDATE users SET name=?, username=?, role=?, password=? WHERE id=? AND school_id=?");
                $stmt->execute([$name, $username, $role, $pass, $id, $school_id]);
            }

        } else {

            if ($school_id == 0) {
                $stmt = $pdo->prepare("UPDATE users SET name=?, username=?, role=? WHERE id=?");
                $stmt->execute([$name, $username, $role, $id]);
            } else {
                $stmt = $pdo->prepare("UPDATE users SET name=?, username=?, role=? WHERE id=? AND school_id=?");
                $stmt->execute([$name, $username, $role, $id, $school_id]);
            }

        }

    } 
    // ================= INSERT =================
    else {

        if ($school_id == 0 && isset($_POST['school_id'])) {
            // super admin manually school select kare
            $school_id_insert = $_POST['school_id'];
        } else {
            $school_id_insert = $school_id;
        }

        $stmt = $pdo->prepare("INSERT INTO users (name, username, role, password, school_id) VALUES (?,?,?,?,?)");
        $stmt->execute([$name, $username, $role, $pass, $school_id_insert]);
    }

    header("Location: index.php?msg=User saved successfully");
}


// ================= DELETE =================
elseif ($action == 'delete' && isset($_GET['id'])) {

    $id = $_GET['id'];

    if ($school_id == 0) {
        $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$id]);
    } else {
        $pdo->prepare("DELETE FROM users WHERE id = ? AND school_id = ?")->execute([$id, $school_id]);
    }

    header("Location: index.php?msg=User deleted successfully");
}

exit;