<?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){
    
// Helper function to create slugs
function slugify($text) {
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    $text = strtolower($text);
    return empty($text) ? 'n-a' : $text;
}

// CSV Import/Export for Coupons and Stores

$action = isset($_GET['action']) ? $_GET['action'] : '';

// Export Coupons to CSV
if ($action == 'export_coupons') {
    $query = $conn->query("SELECT c.*, s.store_title as merchant 
                           FROM coupons c 
                           LEFT JOIN stores s ON c.coupon_store = s.store_id 
                           ORDER BY c.coupon_id DESC");
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=coupons_export_' . date('Y-m-d') . '.csv');
    
    $output = fopen('php://output', 'w');
    
    // CSV Headers
    fputcsv($output, array('Title', 'Merchant', 'Description', 'Coupon Code', 'URL', 'Start Date', 'End Date'));
    
    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($output, array(
            $row['coupon_title'],
            $row['merchant'],
            strip_tags($row['coupon_description']),
            $row['coupon_code'],
            $row['coupon_link'],
            date('d-m-Y', strtotime($row['coupon_start'])),
            $row['coupon_expire'] ? date('d-m-Y', strtotime($row['coupon_expire'])) : ''
        ));
    }
    
    fclose($output);
    exit;
}

// Export Stores to CSV
if ($action == 'export_stores') {
    $query = $conn->query("SELECT * FROM stores ORDER BY store_id DESC");
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=stores_export_' . date('Y-m-d') . '.csv');
    
    $output = fopen('php://output', 'w');
    
    // CSV Headers
    fputcsv($output, array('Store Name', 'Description', 'Slug', 'Featured', 'Status'));
    
    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($output, array(
            $row['store_title'],
            strip_tags($row['store_description']),
            $row['store_slug'],
            $row['store_featured'],
            $row['store_status']
        ));
    }
    
    fclose($output);
    exit;
}

// Import Coupons from CSV
if ($action == 'import_coupons' && isset($_FILES['csv_file'])) {
    $file = $_FILES['csv_file']['tmp_name'];
    $imported = 0;
    $skipped = 0;
    $errors = array();
    
    if (($handle = fopen($file, 'r')) !== FALSE) {
        // Skip header row
        $header = fgetcsv($handle);
        
        while (($data = fgetcsv($handle)) !== FALSE) {
            try {
                // Data mapping: Title, Merchant, Description, Coupon Code, URL, Start Date, End Date
                $title = isset($data[0]) ? trim($data[0]) : '';
                $merchant = isset($data[1]) ? trim($data[1]) : '';
                $description = isset($data[2]) ? trim($data[2]) : '';
                $code = isset($data[3]) ? trim($data[3]) : '';
                $url = isset($data[4]) ? trim($data[4]) : '';
                $start_date = isset($data[5]) ? trim($data[5]) : '';
                $end_date = isset($data[6]) ? trim($data[6]) : '';
                
                if (empty($title) || empty($merchant)) {
                    continue;
                }
                
                // Auto-create store if doesn't exist
                $store_slug = slugify($merchant);
                $store_check = $conn->query("SELECT store_id FROM stores WHERE store_slug = '$store_slug'");
                
                if ($store_check->rowCount() == 0) {
                    // Create new store
                    $store_insert = $conn->prepare("INSERT INTO stores (store_title, store_description, store_slug, store_image, store_status) 
                                                    VALUES (?, ?, ?, 'default-store.png', 1)");
                    $store_insert->execute([$merchant, $merchant, $store_slug]);
                    $store_id = $conn->lastInsertId();
                } else {
                    $store_row = $store_check->fetch(PDO::FETCH_ASSOC);
                    $store_id = $store_row['store_id'];
                }
                
                // Create coupon slug
                $coupon_slug = slugify($title);
                
                // Check if coupon already exists
                $coupon_check = $conn->prepare("SELECT coupon_id FROM coupons WHERE coupon_slug = ? AND coupon_store = ?");
                $coupon_check->execute([$coupon_slug, $store_id]);
                
                if ($coupon_check->rowCount() > 0) {
                    $skipped++;
                    continue;
                }
                
                // Convert dates - Handle multiple date formats
                $start_datetime = date('Y-m-d H:i:s');
                if (!empty($start_date)) {
                    // Try to parse date in multiple formats
                    $start_timestamp = false;
                    
                    // Try dd-mm-yyyy format
                    if (preg_match('/^(\d{1,2})-(\d{1,2})-(\d{4})$/', $start_date, $matches)) {
                        $start_timestamp = mktime(0, 0, 0, $matches[2], $matches[1], $matches[3]);
                    }
                    // Try dd/mm/yyyy format
                    elseif (preg_match('/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/', $start_date, $matches)) {
                        $start_timestamp = mktime(0, 0, 0, $matches[2], $matches[1], $matches[3]);
                    }
                    // Try yyyy-mm-dd format
                    elseif (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $start_date)) {
                        $start_timestamp = strtotime($start_date);
                    }
                    // Try other formats
                    else {
                        $start_timestamp = strtotime($start_date);
                    }
                    
                    if ($start_timestamp && $start_timestamp > 0) {
                        $start_datetime = date('Y-m-d H:i:s', $start_timestamp);
                    }
                }
                
                $expire_datetime = NULL;
                if (!empty($end_date)) {
                    // Try to parse date in multiple formats
                    $expire_timestamp = false;
                    
                    // Try dd-mm-yyyy format
                    if (preg_match('/^(\d{1,2})-(\d{1,2})-(\d{4})$/', $end_date, $matches)) {
                        $expire_timestamp = mktime(23, 59, 59, $matches[2], $matches[1], $matches[3]);
                    }
                    // Try dd/mm/yyyy format
                    elseif (preg_match('/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/', $end_date, $matches)) {
                        $expire_timestamp = mktime(23, 59, 59, $matches[2], $matches[1], $matches[3]);
                    }
                    // Try yyyy-mm-dd format
                    elseif (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $end_date)) {
                        $expire_timestamp = strtotime($end_date . ' 23:59:59');
                    }
                    // Try other formats
                    else {
                        $expire_timestamp = strtotime($end_date);
                    }
                    
                    if ($expire_timestamp && $expire_timestamp > 0) {
                        $expire_datetime = date('Y-m-d H:i:s', $expire_timestamp);
                    }
                }
                
                // Insert coupon
                $insert = $conn->prepare("INSERT INTO coupons 
                    (coupon_title, coupon_description, coupon_store, coupon_slug, coupon_author, 
                     coupon_image, coupon_code, coupon_tagline, coupon_link, coupon_start, coupon_expire, coupon_status) 
                    VALUES (?, ?, ?, ?, 1, 'default-coupon.png', ?, '', ?, ?, ?, 1)");
                
                $insert->execute([
                    $title,
                    $description,
                    $store_id,
                    $coupon_slug,
                    $code,
                    $url,
                    $start_datetime,
                    $expire_datetime
                ]);
                
                $imported++;
                
            } catch (Exception $e) {
                $errors[] = "Error importing row: " . $e->getMessage();
            }
        }
        
        fclose($handle);
    }
    
    $message = "$imported coupons imported successfully!";
    if ($skipped > 0) {
        $message .= " ($skipped duplicates skipped)";
    }
    $_SESSION['import_success'] = $message;
    
    if (!empty($errors)) {
        $_SESSION['import_errors'] = implode('<br>', $errors);
    }
    
    header('Location: ./import_export.php');
    exit;
}

// Import Stores from CSV
if ($action == 'import_stores' && isset($_FILES['csv_file'])) {
    $file = $_FILES['csv_file']['tmp_name'];
    $imported = 0;
    $skipped = 0;
    $errors = array();
    
    if (($handle = fopen($file, 'r')) !== FALSE) {
        // Skip header row
        $header = fgetcsv($handle);
        
        while (($data = fgetcsv($handle)) !== FALSE) {
            try {
                // Data mapping: Store Name, Description, Slug, Featured, Status
                $store_name = isset($data[0]) ? trim($data[0]) : '';
                $description = isset($data[1]) ? trim($data[1]) : '';
                $slug = isset($data[2]) ? trim($data[2]) : '';
                $featured = isset($data[3]) ? (int)$data[3] : 0;
                $status = isset($data[4]) ? (int)$data[4] : 1;
                
                if (empty($store_name)) {
                    continue;
                }
                
                // Generate slug if not provided
                if (empty($slug)) {
                    $slug = slugify($store_name);
                }
                
                // Check if store already exists
                $store_check = $conn->prepare("SELECT store_id FROM stores WHERE store_slug = ?");
                $store_check->execute([$slug]);
                
                if ($store_check->rowCount() > 0) {
                    $skipped++;
                    continue;
                }
                
                // Insert store
                $insert = $conn->prepare("INSERT INTO stores 
                    (store_title, store_description, store_slug, store_image, store_featured, store_status) 
                    VALUES (?, ?, ?, 'default-store.png', ?, ?)");
                
                $insert->execute([
                    $store_name,
                    $description,
                    $slug,
                    $featured,
                    $status
                ]);
                
                $imported++;
                
            } catch (Exception $e) {
                $errors[] = "Error importing row: " . $e->getMessage();
            }
        }
        
        fclose($handle);
    }
    
    $message = "$imported stores imported successfully!";
    if ($skipped > 0) {
        $message .= " ($skipped duplicates skipped)";
    }
    $_SESSION['import_success'] = $message;
    
    if (!empty($errors)) {
        $_SESSION['import_errors'] = implode('<br>', $errors);
    }
    
    header('Location: ./import_export.php');
    exit;
}

// Upload Store Image from URL
if ($action == 'upload_store_image' && isset($_POST['store_id']) && isset($_POST['image_url'])) {
    $store_id = $_POST['store_id'];
    $image_url = $_POST['image_url'];
    
    try {
        // Download image from URL
        $image_content = @file_get_contents($image_url);
        
        if ($image_content === FALSE) {
            $_SESSION['import_errors'] = "Failed to download image from URL. Please check the URL and try again.";
            header('Location: ./import_export.php');
            exit;
        }
        
        // Get image extension
        $image_info = getimagesize($image_url);
        $extension = image_type_to_extension($image_info[2], false);
        
        // Generate unique filename
        $filename = 'store_' . $store_id . '_' . time() . '.' . $extension;
        $upload_path = '../../images/' . $filename;
        
        // Save image
        if (file_put_contents($upload_path, $image_content)) {
            // Update store with new image
            $update = $conn->prepare("UPDATE stores SET store_image = ? WHERE store_id = ?");
            $update->execute([$filename, $store_id]);
            
            $_SESSION['import_success'] = "Store image uploaded successfully!";
        } else {
            $_SESSION['import_errors'] = "Failed to save image. Please check folder permissions.";
        }
        
    } catch (Exception $e) {
        $_SESSION['import_errors'] = "Error uploading image: " . $e->getMessage();
    }
    
    header('Location: ./import_export.php');
    exit;
}

// Get statistics
$total_coupons = $conn->query("SELECT COUNT(*) as count FROM coupons")->fetch(PDO::FETCH_ASSOC)['count'];
$total_stores = $conn->query("SELECT COUNT(*) as count FROM stores")->fetch(PDO::FETCH_ASSOC)['count'];

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

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

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

?>
