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


function getOffers($uid, $amt = 0) {
    $db = getDBConnection();
    $db->prepare("UPDATE offers SET status = 'expired' WHERE end_date < CURDATE() AND status = 'active'")->execute();
    
    $u = $db->prepare("SELECT u.*, COUNT(o.id) as oc FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.id = ? GROUP BY u.id");
    $u->execute([$uid]);
    $user = $u->fetch();
    if (!$user) return [];
    
    $type = 'new';
    if ($user['oc'] >= 5) $type = 'regular';
    else if ($user['oc'] > 0) $type = 'normal';
    
    $o = $db->prepare("SELECT * FROM offers WHERE status = 'active' AND start_date <= CURDATE() AND end_date >= CURDATE() AND (target_customers = 'all' OR target_customers = ?) AND min_order_amount <= ? ORDER BY discount_value DESC");
    $o->execute([$type, $amt]);
    return $o->fetchAll();
}


function calcDisc($off, $amt) {
    if ($amt < $off['min_order_amount']) return 0;
    $d = $off['discount_type'] === 'percentage' ? ($amt * $off['discount_value']) / 100 : $off['discount_value'];
    if ($off['max_discount_amount'] && $d > $off['max_discount_amount']) $d = $off['max_discount_amount'];
    return min($d, $amt);
}


function applyBestOffer($userId, $orderAmount) {
    $offers = getOffers($userId, $orderAmount);
    
    if (empty($offers)) {
        return [
            'offer_id' => null,
            'offer_title' => null,
            'discount_amount' => 0,
            'final_amount' => $orderAmount
        ];
    }
    
    $bestOffer = null;
    $bestDiscount = 0;
    
    foreach ($offers as $offer) {
        $discount = calcDisc($offer, $orderAmount);
        if ($discount > $bestDiscount) {
            $bestDiscount = $discount;
            $bestOffer = $offer;
        }
    }
    
    return [
        'offer_id' => $bestOffer ? $bestOffer['id'] : null,
        'offer_title' => $bestOffer ? $bestOffer['title'] : null,
        'discount_amount' => $bestDiscount,
        'final_amount' => $orderAmount - $bestDiscount
    ];
}


function markOfferAsUsed($offerId) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("UPDATE offers SET used_count = used_count + 1 WHERE id = ?");
        return $stmt->execute([$offerId]);
    } catch (Exception $e) {
        error_log("Error in markOfferAsUsed: " . $e->getMessage());
        return false;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    if (!User::isLoggedIn()) {
        echo json_encode(['success' => false, 'error' => 'Please login first']);
        exit();
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
    
    switch ($action) {
        case 'get_available_offers':
            $userId = User::getCurrentUser()['id'];
            $orderAmount = floatval($input['order_amount'] ?? 0);
            
            $offers = getOffers($userId, $orderAmount);
            $result = [];
            
            foreach ($offers as $offer) {
                $discount = calcDisc($offer, $orderAmount);
                $result[] = [
                    'id' => $offer['id'],
                    'title' => $offer['title'],
                    'description' => $offer['description'],
                    'discount_type' => $offer['discount_type'],
                    'discount_value' => $offer['discount_value'],
                    'applicable_services' => $offer['applicable_services'],
                    'calculated_discount' => $discount,
                    'final_amount' => $orderAmount - $discount
                ];
            }
            
            echo json_encode(['success' => true, 'offers' => $result]);
            break;
            
        case 'apply_offer':
            $userId = User::getCurrentUser()['id'];
            $orderAmount = floatval($input['order_amount'] ?? 0);
            
            $result = applyBestOffer($userId, $orderAmount);
            echo json_encode(['success' => true, 'result' => $result]);
            break;
            
        default:
            echo json_encode(['success' => false, 'error' => 'Invalid action']);
            break;
    }
}
?>
