<?php

session_start();

require '../../config.php';
require '../admin_config.php';
require '../functions.php';

if (isset($_SESSION['user_email'])){

$conn = connect($database);
if(!$conn){
    header('Location: ../error.php');
    exit;
}

$check_access = check_access($conn);

if ($check_access['user_role'] == 1 || $check_access['user_role'] == 2){

if (isset($_GET['id'])) {
    $campaign_id = (int)$_GET['id'];
    
    // Get campaign image to delete file
    $query = $conn->prepare("SELECT campaign_image FROM campaigns WHERE campaign_id = ?");
    $query->execute([$campaign_id]);
    $campaign = $query->fetch(PDO::FETCH_ASSOC);
    
    if ($campaign) {
        // Delete campaign
        $delete = $conn->prepare("DELETE FROM campaigns WHERE campaign_id = ?");
        
        if ($delete->execute([$campaign_id])) {
            // Delete image file if not default
            if ($campaign['campaign_image'] != 'default-campaign.png') {
                $image_path = '../../images/' . $campaign['campaign_image'];
                if (file_exists($image_path)) {
                    unlink($image_path);
                }
            }
            
            $_SESSION['campaign_success'] = 'Campaign deleted successfully!';
        } else {
            $_SESSION['campaign_error'] = 'Failed to delete campaign.';
        }
    } else {
        $_SESSION['campaign_error'] = 'Campaign not found.';
    }
}

header('Location: ./campaigns.php');
exit;

}else{
    header('Location:'.SITE_URL);
}

}else{
    header('Location: ../login.php');
}

?>

