<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0); 

require_once '../includes/User.php';
require_once '../includes/db_config.php';

ob_clean();
header('Content-Type: application/json');

if (!User::isLoggedIn() || !User::isAdmin()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized access']);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];

try {
    $pdo = getDBConnection();
    
    $stmt = $pdo->prepare("UPDATE offers SET status = 'expired' WHERE end_date < CURDATE() AND status = 'active'");
    $stmt->execute();
    
    switch ($method) {
        case 'GET':
            if (isset($_GET['id'])) {
                $stmt = $pdo->prepare("SELECT * FROM offers WHERE id = ?");
                $stmt->execute([$_GET['id']]);
                $offer = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($offer) {
                    echo json_encode(['success' => true, 'data' => $offer]);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Offer not found']);
                }
            } else {
                $stmt = $pdo->prepare("
                    SELECT * FROM offers 
                    ORDER BY created_at DESC 
                    LIMIT 50
                ");
                $stmt->execute();
                $offers = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode(['success' => true, 'data' => $offers]);
            }
            break;
            
        case 'POST':
            $rawInput = file_get_contents('php://input');
            $input = json_decode($rawInput, true);
            
            if ($input && json_last_error() === JSON_ERROR_NONE) {
                $data = $input;
            } else {
                $data = $_POST;
            }
            
            if (isset($data['action'])) {
                switch ($data['action']) {
                    case 'toggle_status':
                        if (!isset($data['id']) || !isset($data['status'])) {
                            echo json_encode(['success' => false, 'error' => 'Offer ID and status are required']);
                            exit();
                        }
                        
                        $stmt = $pdo->prepare("UPDATE offers SET status = ? WHERE id = ?");
                        $result = $stmt->execute([$data['status'], $data['id']]);
                        
                        if ($result) {
                            echo json_encode(['success' => true, 'message' => 'Offer status updated successfully']);
                        } else {
                            echo json_encode(['success' => false, 'error' => 'Failed to update offer status']);
                        }
                        exit();
                        
                    case 'send_notifications':
                        $stmt = $pdo->prepare("
                            SELECT * FROM offers 
                            WHERE status = 'active' 
                            AND start_date <= CURDATE() 
                            AND end_date >= CURDATE()
                        ");
                        $stmt->execute();
                        $activeOffers = $stmt->fetchAll(PDO::FETCH_ASSOC);
                        
                        if (empty($activeOffers)) {
                            echo json_encode(['success' => false, 'error' => 'No active offers to send']);
                            exit();
                        }
                        
                        $stmt = $pdo->prepare("
                            SELECT u.id, u.name, u.email,
                                   COUNT(o.id) as order_count,
                                   CASE 
                                       WHEN EXISTS(SELECT 1 FROM subscriptions s WHERE s.user_id = u.id AND s.status = 'active') THEN 'subscribed'
                                       WHEN COUNT(o.id) >= 5 THEN 'regular'
                                       WHEN COUNT(o.id) > 0 THEN 'normal'
                                       ELSE 'new'
                                   END as customer_type
                            FROM users u 
                            LEFT JOIN orders o ON u.id = o.user_id 
                            WHERE u.role = 'user'
                            GROUP BY u.id
                        ");
                        $stmt->execute();
                        $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
                        
                        $notificationCount = 0;
                        
                        foreach ($customers as $customer) {
                            $applicableOffers = [];
                            
                            foreach ($activeOffers as $offer) {
                                if ($offer['target_customers'] === 'all' || $offer['target_customers'] === $customer['customer_type']) {
                                    $applicableOffers[] = $offer;
                                }
                            }
                            
                            if (!empty($applicableOffers)) {
                                $offerTitles = array_column($applicableOffers, 'title');
                                $message = "New offers available for you: " . implode(', ', array_slice($offerTitles, 0, 3));
                                if (count($offerTitles) > 3) {
                                    $message .= " and " . (count($offerTitles) - 3) . " more!";
                                }
                                
                                $stmt = $pdo->prepare("
                                    INSERT INTO notifications (user_id, title, message, type, created_at) 
                                    VALUES (?, ?, ?, ?, NOW())
                                ");
                                $stmt->execute([
                                    $customer['id'],
                                    'Special Offers Available!',
                                    $message,
                                    'info'
                                ]);
                                $notificationCount++;
                            }
                        }
                        
                        echo json_encode([
                            'success' => true, 
                            'message' => 'Notifications sent successfully',
                            'count' => $notificationCount
                        ]);
                        exit();
                        
                    case 'send_single_offer':
                        if (!isset($data['offer_id'])) {
                            echo json_encode(['success' => false, 'error' => 'Offer ID is required']);
                            exit();
                        }
                        
                        $stmt = $pdo->prepare("SELECT * FROM offers WHERE id = ? AND status = 'active'");
                        $stmt->execute([$data['offer_id']]);
                        $offer = $stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if (!$offer) {
                            echo json_encode(['success' => false, 'error' => 'Offer not found or inactive']);
                            exit();
                        }
                        
                        $stmt = $pdo->prepare("
                            SELECT u.id, u.name, u.email,
                                   COUNT(o.id) as order_count,
                                   CASE 
                                       WHEN EXISTS(SELECT 1 FROM subscriptions s WHERE s.user_id = u.id AND s.status = 'active') THEN 'subscribed'
                                       WHEN COUNT(o.id) >= 5 THEN 'regular'
                                       WHEN COUNT(o.id) > 0 THEN 'normal'
                                       ELSE 'new'
                                   END as customer_type
                            FROM users u 
                            LEFT JOIN orders o ON u.id = o.user_id 
                            WHERE u.role = 'user'
                            GROUP BY u.id
                        ");
                        $stmt->execute();
                        $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
                        
                        $notificationCount = 0;
                        
                        foreach ($customers as $customer) {
                            if ($offer['target_customers'] === 'all' || $offer['target_customers'] === $customer['customer_type']) {
                                $stmt = $pdo->prepare("
                                    INSERT INTO notifications (user_id, title, message, type, created_at) 
                                    VALUES (?, ?, ?, ?, NOW())
                                ");
                                $stmt->execute([
                                    $customer['id'],
                                    $offer['title'],
                                    $offer['description'] . ' - ' . $offer['discount_value'] . ($offer['discount_type'] === 'percentage' ? '% off' : '$ off'),
                                    'info'
                                ]);
                                $notificationCount++;
                            }
                        }
                        
                        echo json_encode([
                            'success' => true, 
                            'message' => 'Notification sent successfully',
                            'count' => $notificationCount
                        ]);
                        exit();
                }
            }
            
            if (isset($data['id']) && !empty($data['id'])) {
                error_log("Updating offer with data: " . print_r($data, true));
                $stmt = $pdo->prepare("
                    UPDATE offers 
                    SET title = ?, description = ?, discount_type = ?, discount_value = ?, 
                        min_order_amount = ?, max_discount_amount = ?, start_date = ?, 
                        end_date = ?, usage_limit = ?, target_customers = ?, 
                        applicable_services = ?, status = ?
                    WHERE id = ?
                ");
                $result = $stmt->execute([
                    $data['title'],
                    $data['description'],
                    $data['discount_type'],
                    $data['discount_value'],
                    $data['min_order_amount'] ?? 0,
                    $data['max_discount_amount'] ?: null,
                    $data['start_date'],
                    $data['end_date'],
                    $data['usage_limit'] ?: null,
                    $data['target_customers'],
                    $data['applicable_services'] ?: null,
                    $data['status'] ?? 'active',
                    $data['id']
                ]);
                
                if ($result) {
                    echo json_encode(['success' => true, 'message' => 'Offer updated successfully']);
                } else {
                    $errorInfo = $stmt->errorInfo();
                    error_log("Failed to update offer: " . print_r($errorInfo, true));
                    echo json_encode(['success' => false, 'error' => 'Failed to update offer: ' . $errorInfo[2]]);
                }
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO offers (title, description, discount_type, discount_value, 
                                      min_order_amount, max_discount_amount, start_date, end_date, 
                                      usage_limit, target_customers, applicable_services, status) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $result = $stmt->execute([
                    $data['title'],
                    $data['description'],
                    $data['discount_type'],
                    $data['discount_value'],
                    $data['min_order_amount'] ?? 0,
                    $data['max_discount_amount'] ?: null,
                    $data['start_date'],
                    $data['end_date'],
                    $data['usage_limit'] ?: null,
                    $data['target_customers'],
                    $data['applicable_services'] ?: null,
                    $data['status'] ?? 'active'
                ]);
                
                if ($result) {
                    echo json_encode(['success' => true, 'message' => 'Offer created successfully']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Failed to create offer']);
                }
            }
            break;
            
        case 'PUT':
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($input['id']) || !isset($input['status'])) {
                echo json_encode(['success' => false, 'error' => 'Offer ID and status are required']);
                exit();
            }
            
            $stmt = $pdo->prepare("UPDATE offers SET status = ? WHERE id = ?");
            $result = $stmt->execute([$input['status'], $input['id']]);
            
            if ($result) {
                echo json_encode(['success' => true, 'message' => 'Offer status updated successfully']);
            } else {
                echo json_encode(['success' => false, 'error' => 'Failed to update offer status']);
            }
            break;
            
        case 'DELETE':
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($input['id'])) {
                echo json_encode(['success' => false, 'error' => 'Offer ID is required']);
                exit();
            }
            
            $stmt = $pdo->prepare("DELETE FROM offers WHERE id = ?");
            $result = $stmt->execute([$input['id']]);
            
            if ($result) {
                echo json_encode(['success' => true, 'message' => 'Offer deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'error' => 'Failed to delete offer']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'error' => 'Method not allowed']);
            break;
    }
    
} catch (PDOException $e) {
    error_log("PDO Error in manage_offers.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    error_log("General Error in manage_offers.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Error: ' . $e->getMessage()]);
} catch (Error $e) {
    error_log("Fatal Error in manage_offers.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Fatal error occurred']);
}

ob_end_flush();
?>
