<?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){

$errors = array();

if (!isset($_GET['id'])) {
    header('Location: ./popups.php');
    exit;
}

$popup_id = intval($_GET['id']);

// Get popup data
$stmt = $connect->prepare("SELECT * FROM popups WHERE popup_id = ?");
$stmt->execute([$popup_id]);
$popup = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$popup) {
    $_SESSION['popup_error'] = 'Popup not found';
    header('Location: ./popups.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    
    $popup_title = trim($_POST['popup_title']);
    $popup_type = $_POST['popup_type'];
    $popup_content = $_POST['popup_content'];
    $popup_button_text = trim($_POST['popup_button_text']);
    $popup_button_link = trim($_POST['popup_button_link']);
    $popup_delay = intval($_POST['popup_delay']);
    $popup_frequency = $_POST['popup_frequency'];
    $popup_position = $_POST['popup_position'];
    $popup_width = trim($_POST['popup_width']);
    $popup_enabled = isset($_POST['popup_enabled']) ? 1 : 0;
    $popup_show_on_pages = $_POST['popup_show_on_pages'];
    $popup_device = isset($_POST['popup_device']) ? $_POST['popup_device'] : 'both';
    $popup_priority = intval($_POST['popup_priority']);
    $popup_start_date = !empty($_POST['popup_start_date']) ? $_POST['popup_start_date'] : NULL;
    $popup_end_date = !empty($_POST['popup_end_date']) ? $_POST['popup_end_date'] : NULL;
    
    // Handle image upload
    $popup_image = $popup['popup_image']; // Keep existing image
    
    if (isset($_FILES['popup_image']) && $_FILES['popup_image']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $filename = $_FILES['popup_image']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $new_filename = 'popup_' . time() . '.' . $ext;
            $upload_path = '../../images/' . $new_filename;
            
            if (move_uploaded_file($_FILES['popup_image']['tmp_name'], $upload_path)) {
                // Delete old image if exists
                if ($popup_image && file_exists('../../images/' . $popup_image)) {
                    unlink('../../images/' . $popup_image);
                }
                $popup_image = $new_filename;
            }
        }
    }
    
    // Handle image removal
    if (isset($_POST['remove_image']) && $popup_image) {
        if (file_exists('../../images/' . $popup_image)) {
            unlink('../../images/' . $popup_image);
        }
        $popup_image = NULL;
    }
    
    if (empty($popup_title)) {
        $errors[] = 'Popup title is required';
    }
    
    // Handle CDN fields
    $popup_image_cdn_url = isset($_POST['popup_image_cdn_url']) ? cleardata($_POST['popup_image_cdn_url']) : '';
    $popup_use_cdn = isset($_POST['popup_use_cdn']) ? 1 : 0;
    
    if (empty($errors)) {
        $stmt = $connect->prepare("UPDATE popups SET 
            popup_title = ?, popup_type = ?, popup_content = ?, popup_image = ?, 
            popup_button_text = ?, popup_button_link = ?, popup_delay = ?, popup_frequency = ?, 
            popup_position = ?, popup_width = ?, popup_enabled = ?, popup_show_on_pages = ?, popup_device = ?,
            popup_start_date = ?, popup_end_date = ?, popup_priority = ?, popup_image_cdn_url = ?, popup_use_cdn = ?, popup_updated_at = NOW()
            WHERE popup_id = ?
        ");
        
        $stmt->execute([
            $popup_title, $popup_type, $popup_content, $popup_image,
            $popup_button_text, $popup_button_link, $popup_delay, $popup_frequency,
            $popup_position, $popup_width, $popup_enabled, $popup_show_on_pages, $popup_device,
            $popup_start_date, $popup_end_date, $popup_priority, $popup_image_cdn_url, $popup_use_cdn, $popup_id
        ]);
        
        $_SESSION['popup_success'] = 'Popup updated successfully!';
        header('Location: ./popups.php');
        exit;
    }
}

require '../views/header.view.php';
require '../views/edit_popup.view.php';

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

require '../views/footer.view.php';

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

?>
