<?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'];
        
        $db_auth->exec("USE " . DB_AUTH_NAME);

        // Hard delete marketing (menghapus data secara permanen)
        $stmt = $db_auth->prepare("
            DELETE FROM marketing 
            WHERE id = ? AND supervisor_id = ?
        ");
        $stmt->execute([$marketing_id, $_SESSION['user_id']]);

        if ($stmt->rowCount() > 0) {
            // Dapatkan ID maksimum yang ada
            $maxIdStmt = $db_auth->query("SELECT MAX(id) as max_id FROM marketing");
            $maxId = $maxIdStmt->fetch(PDO::FETCH_ASSOC)['max_id'];
            
            // Jika tidak ada data, set AUTO_INCREMENT ke 1
            // Jika ada data, set AUTO_INCREMENT ke max_id + 1
            $nextId = $maxId ? $maxId + 1 : 1;
            
            // Reset AUTO_INCREMENT
            $db_auth->query("ALTER TABLE marketing AUTO_INCREMENT = $nextId");
            
            $_SESSION['success'] = "Marketing deleted successfully!";
        } else {
            throw new Exception("Marketing not found!");
        }
    } catch (Exception $e) {
        $_SESSION['error'] = $e->getMessage();
    }
}

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