<?php
session_start();

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

// Check if user is logged in
if (!isset($_SESSION['user_email'])) {
    header('Location: ../login.php');
    exit();
}

$connect = connect($database);
$check_access = check_access($connect);

if ($check_access['user_role'] != 1 && $check_access['user_role'] != 2) {
    header('Location: ../login.php');
    exit();
}

$user = $check_access;

$message = '';
$error = '';
$fetched_coupons = [];
$import_stats = [
    'total' => 0,
    'imported' => 0,
    'skipped' => 0,
    'errors' => 0
];

// Fetch CueLinks settings
try {
    $stmt = $connect->prepare("SELECT cuelinks_email, cuelinks_api_key, cuelinks_enabled FROM settings WHERE st_id = 1");
    $stmt->execute();
    $cuelinks_settings = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error = 'Failed to load CueLinks settings: ' . $e->getMessage();
    $cuelinks_settings = null;
}

// Handle fetch request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    if ($_POST['action'] === 'fetch') {
        if (!$cuelinks_settings || !$cuelinks_settings['cuelinks_enabled']) {
            $error = 'CueLinks integration is not enabled. Please configure it first.';
        } elseif (empty($cuelinks_settings['cuelinks_email']) || empty($cuelinks_settings['cuelinks_api_key'])) {
            $error = 'CueLinks credentials are missing. Please configure them first.';
        } else {
            // Fetch coupons from CueLinks API
            $fetched_coupons = fetchCueLinksOffers(
                $cuelinks_settings['cuelinks_email'],
                $cuelinks_settings['cuelinks_api_key']
            );
            
            if ($fetched_coupons === false) {
                $error = 'Failed to fetch coupons from CueLinks API. Please check your credentials.';
            } else {
                $import_stats['total'] = count($fetched_coupons);
                $message = 'Successfully fetched ' . $import_stats['total'] . ' coupons from CueLinks!';
            }
        }
    }
    
    if ($_POST['action'] === 'import' && isset($_POST['selected_coupons'])) {
        $selected_coupons = json_decode($_POST['selected_coupons'], true);
        
        foreach ($selected_coupons as $coupon_data) {
            try {
                $result = importCueLinksCoupon($connect, $coupon_data);
                if ($result === true) {
                    $import_stats['imported']++;
                } elseif ($result === 'skipped') {
                    $import_stats['skipped']++;
                } else {
                    $import_stats['errors']++;
                }
            } catch (Exception $e) {
                $import_stats['errors']++;
            }
        }
        
        $message = sprintf(
            'Import completed: %d imported, %d skipped, %d errors',
            $import_stats['imported'],
            $import_stats['skipped'],
            $import_stats['errors']
        );
    }
}

/**
 * Fetch offers from CueLinks API
 */
function fetchCueLinksOffers($email, $api_key) {
    // CueLinks API endpoint (adjust based on actual API documentation)
    $api_url = 'https://api.cuelinks.com/api/v2/offers';
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $api_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $api_key,
            'Content-Type: application/json',
            'X-User-Email: ' . $email
        ],
        CURLOPT_TIMEOUT => 30
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($http_code === 200 && $response) {
        $data = json_decode($response, true);
        return $data['offers'] ?? $data['data'] ?? [];
    }
    
    return false;
}

/**
 * Import a single coupon from CueLinks
 */
function importCueLinksCoupon($connect, $coupon_data) {
    // Check if coupon already exists
    $check = $connect->prepare("SELECT coupon_id FROM coupons WHERE coupon_code = ? OR coupon_link = ?");
    $check->execute([
        $coupon_data['code'] ?? '',
        $coupon_data['link'] ?? ''
    ]);
    
    if ($check->fetch()) {
        return 'skipped'; // Already exists
    }
    
    // Find or create store
    $store_id = findOrCreateStore($connect, $coupon_data['merchant'] ?? 'Unknown Store');
    
    // Prepare coupon data
    $stmt = $connect->prepare("
        INSERT INTO coupons (
            coupon_title,
            coupon_tagline,
            coupon_code,
            coupon_link,
            coupon_type,
            coupon_expire,
            coupon_start,
            coupon_image,
            coupon_store,
            coupon_exclusive,
            coupon_verify,
            coupon_featured,
            coupon_status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $result = $stmt->execute([
        $coupon_data['title'] ?? 'Special Offer',
        $coupon_data['description'] ?? '',
        $coupon_data['code'] ?? '',
        $coupon_data['link'] ?? '',
        !empty($coupon_data['code']) ? 'coupon' : 'deal',
        $coupon_data['end_date'] ?? date('Y-m-d', strtotime('+30 days')),
        date('Y-m-d'),
        $coupon_data['image'] ?? '',
        $store_id,
        0, // exclusive
        1, // verified
        0, // featured
        1  // active
    ]);
    
    return $result ? true : false;
}

/**
 * Find existing store or create new one
 */
function findOrCreateStore($connect, $store_name) {
    // Try to find existing store
    $stmt = $connect->prepare("SELECT store_id FROM stores WHERE store_title = ?");
    $stmt->execute([$store_name]);
    $store = $stmt->fetch();
    
    if ($store) {
        return $store['store_id'];
    }
    
    // Create new store
    $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $store_name));
    $stmt = $connect->prepare("
        INSERT INTO stores (store_title, store_slug, store_status) 
        VALUES (?, ?, 1)
    ");
    $stmt->execute([$store_name, $slug]);
    
    return $connect->lastInsertId();
}

require '../views/cuelinks_fetch.view.php';
?>
