<?php

session_start();

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

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

$connect = connect($database);

$check_access = check_access($connect);

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

if (isset($_GET['id'])){
    
    $popup_id = intval($_GET['id']);
    
    // Get popup image to delete
    $stmt = $connect->prepare("SELECT popup_image FROM popups WHERE popup_id = ?");
    $stmt->execute([$popup_id]);
    $popup = $stmt->fetch();
    
    // Delete image file if exists
    if ($popup && $popup['popup_image']) {
        $image_path = '../../images/' . $popup['popup_image'];
        if (file_exists($image_path)) {
            unlink($image_path);
        }
    }
    
    // Delete popup
    $stmt = $connect->prepare("DELETE FROM popups WHERE popup_id = ?");
    $stmt->execute([$popup_id]);
    
    // Delete related views and clicks
    $connect->query("DELETE FROM popup_views WHERE popup_id = $popup_id");
    $connect->query("DELETE FROM popup_clicks WHERE popup_id = $popup_id");
    
    $_SESSION['popup_success'] = 'Popup deleted successfully!';
}

header('Location: ./popups.php');

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

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

?>
