<?php
require_once 'includes/config.php';
session_start();

// Cek role supervisor
if ($_SESSION['role'] !== 'supervisor') {
    $_SESSION['error'] = "Unauthorized access!";
    header("Location: users.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verifikasi CSRF token
    if (!verifyCSRFToken($_POST['csrf_token'])) {
        $_SESSION['error'] = "Invalid security token!";
        header("Location: users.php");
        exit();
    }

    try {
        $marketing_id = $_POST['marketing_id'];
        $username = sanitize_input($_POST['username']);
        $nama_lengkap = sanitize_input($_POST['nama_lengkap']);
        $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
        $password = $_POST['password'];
        $password_confirmation = $_POST['password_confirmation'];

        $db_auth->exec("USE " . DB_AUTH_NAME);

        // Cek apakah marketing dimiliki oleh supervisor ini
        $stmt = $db_auth->prepare("SELECT id FROM marketing WHERE id = ? AND supervisor_id = ?");
        $stmt->execute([$marketing_id, $_SESSION['user_id']]);
        if (!$stmt->fetch()) {
            throw new Exception("Marketing not found!");
        }

        // Cek username unik (kecuali untuk marketing yang sedang diedit)
        $stmt = $db_auth->prepare("SELECT id FROM marketing WHERE username = ? AND id != ?");
        $stmt->execute([$username, $marketing_id]);
        if ($stmt->fetch()) {
            throw new Exception("Username is already taken!");
        }

        // Cek email unik (kecuali untuk marketing yang sedang diedit)
        $stmt = $db_auth->prepare("SELECT id FROM marketing WHERE email = ? AND id != ?");
        $stmt->execute([$email, $marketing_id]);
        if ($stmt->fetch()) {
            throw new Exception("Email is already taken!");
        }

        // Update data
        if (!empty($password)) {
            // Validasi password jika diisi
            if (strlen($password) < 6) {
                throw new Exception("Password must be at least 6 characters!");
            }
            if ($password !== $password_confirmation) {
                throw new Exception("Password confirmation does not match!");
            }

            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $db_auth->prepare("
                UPDATE marketing 
                SET username = ?, nama_lengkap = ?, email = ?, password = ? 
                WHERE id = ? AND supervisor_id = ?
            ");
            $stmt->execute([$username, $nama_lengkap, $email, $hash, $marketing_id, $_SESSION['user_id']]);
        } else {
            $stmt = $db_auth->prepare("
                UPDATE marketing 
                SET username = ?, nama_lengkap = ?, email = ? 
                WHERE id = ? AND supervisor_id = ?
            ");
            $stmt->execute([$username, $nama_lengkap, $email, $marketing_id, $_SESSION['user_id']]);
        }

        $_SESSION['success'] = "Marketing updated successfully!";
    } catch (Exception $e) {
        $_SESSION['error'] = $e->getMessage();
    }
}

header("Location: users.php");
exit();
 