<?php
/**
 * CALCULATE PRICE API
 * File: api/calculate-price.php
 * Calculate rental price based on item, dates, and extras
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../app/Core/init.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Get request data
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    $input = $_POST;
}

// Validate required fields
$required_fields = ['item_id', 'start_date', 'end_date'];
foreach ($required_fields as $field) {
    if (empty($input[$field])) {
        http_response_code(400);
        echo json_encode(['error' => "Field '$field' is required"]);
        exit;
    }
}

try {
    $item_id = (int)$input['item_id'];
    $start_date = $input['start_date'];
    $end_date = $input['end_date'];
    $quantity = isset($input['quantity']) ? max(1, (int)$input['quantity']) : 1;
    $extras = isset($input['extras']) ? $input['extras'] : [];
    
    // Validate dates
    $start = new DateTime($start_date);
    $end = new DateTime($end_date);
    
    if ($start >= $end) {
        http_response_code(400);
        echo json_encode(['error' => 'End date must be after start date']);
        exit;
    }
    
    $today = new DateTime();
    $today->setTime(0, 0, 0);
    $start->setTime(0, 0, 0);
    
    if ($start < $today) {
        http_response_code(400);
        echo json_encode(['error' => 'Start date cannot be in the past']);
        exit;
    }
    
    // Calculate days
    $interval = $start->diff($end);
    $days = $interval->days;
    
    if ($days < 1) {
        http_response_code(400);
        echo json_encode(['error' => 'Minimum rental period is 1 day']);
        exit;
    }
    
    // Get item details
    $item = new Item();
    $item_data = $item->find($item_id);
    
    if (!$item_data) {
        http_response_code(404);
        echo json_encode(['error' => 'Item not found']);
        exit;
    }
    
    if ($item_data['approval_status'] !== 'approved') {
        http_response_code(400);
        echo json_encode(['error' => 'Item is not available for rent']);
        exit;
    }
    
    if ($item_data['available_quantity'] < $quantity) {
        http_response_code(400);
        echo json_encode(['error' => 'Insufficient quantity available']);
        exit;
    }
    
    // Check availability
    $db = Database::getInstance();
    $availability_sql = "SELECT COUNT(*) as overlap_count 
                        FROM orders 
                        WHERE item_id = ? 
                        AND status NOT IN ('cancelled', 'rejected')
                        AND (
                            (start_date <= ? AND end_date >= ?) OR
                            (start_date <= ? AND end_date >= ?) OR
                            (start_date >= ? AND end_date <= ?)
                        )";
    
    $params = [
        $item_id,
        $start_date, $start_date,  // Check if start date overlaps existing order
        $end_date, $end_date,      // Check if end date overlaps existing order
        $start_date, $end_date     // Check if order is within existing order
    ];
    
    $overlap = $db->fetch($availability_sql, $params);
    
    if ($overlap['overlap_count'] > 0) {
        http_response_code(400);
        echo json_encode(['error' => 'Item is not available for the selected dates']);
        exit;
    }
    
    // Base price calculation
    $base_price_per_day = (float)$item_data['price_per_day'];
    $base_total = $base_price_per_day * $days * $quantity;
    
    // Price adjustments
    $price_adjustments = [];
    $subtotal = $base_total;
    
    // Weekly discount (7+ days)
    if ($days >= 7) {
        $weekly_discount = $subtotal * 0.10; // 10% discount
        $price_adjustments[] = [
            'type' => 'discount',
            'label' => 'Weekly Discount (10%)',
            'amount' => -$weekly_discount
        ];
        $subtotal -= $weekly_discount;
    }
    
    // Monthly discount (30+ days)
    if ($days >= 30) {
        $monthly_discount = $subtotal * 0.20; // 20% discount
        $price_adjustments[] = [
            'type' => 'discount',
            'label' => 'Monthly Discount (20%)',
            'amount' => -$monthly_discount
        ];
        $subtotal -= $monthly_discount;
    }
    
    // Calculate extras
    $extras_total = 0;
    $extras_details = [];
    
    if (!empty($extras) && is_array($extras)) {
        foreach ($extras as $extra_id => $extra_data) {
            if (is_array($extra_data)) {
                $extra_name = $extra_data['name'] ?? 'Extra';
                $extra_price = (float)($extra_data['price'] ?? 0);
                $extra_type = $extra_data['type'] ?? 'daily'; // daily, one-time, per-unit
                
                switch ($extra_type) {
                    case 'daily':
                        $extra_amount = $extra_price * $days * $quantity;
                        break;
                    case 'one-time':
                        $extra_amount = $extra_price;
                        break;
                    case 'per-unit':
                        $extra_amount = $extra_price * $quantity;
                        break;
                    default:
                        $extra_amount = $extra_price;
                }
                
                $extras_total += $extra_amount;
                $extras_details[] = [
                    'id' => $extra_id,
                    'name' => $extra_name,
                    'price' => $extra_price,
                    'type' => $extra_type,
                    'amount' => $extra_amount,
                    'quantity' => $quantity
                ];
            }
        }
    }
    
    $subtotal += $extras_total;
    
    // Platform commission (5% for customers)
    $platform_commission = $subtotal * 0.05;
    $price_adjustments[] = [
        'type' => 'fee',
        'label' => 'Service Fee (5%)',
        'amount' => $platform_commission
    ];
    
    // Tax (7.5% VAT)
    $taxable_amount = $subtotal + $platform_commission;
    $tax = $taxable_amount * 0.075;
    $price_adjustments[] = [
        'type' => 'tax',
        'label' => 'VAT (7.5%)',
        'amount' => $tax
    ];
    
    // Total
    $total = $subtotal + $platform_commission + $tax;
    
    // Deposit (20% of subtotal)
    $deposit = $subtotal * 0.20;
    $price_adjustments[] = [
        'type' => 'deposit',
        'label' => 'Security Deposit (refundable)',
        'amount' => $deposit
    ];
    
    // Early bird discount (book 30+ days in advance)
    $days_in_advance = $start->diff($today)->days;
    if ($days_in_advance >= 30) {
        $early_bird_discount = $total * 0.05; // 5% discount
        $price_adjustments[] = [
            'type' => 'discount',
            'label' => 'Early Bird Discount (5%)',
            'amount' => -$early_bird_discount
        ];
        $total -= $early_bird_discount;
    }
    
    // Prepare response
    $response = [
        'success' => true,
        'calculation' => [
            'item_id' => $item_id,
            'item_title' => $item_data['title'],
            'rental_period' => [
                'start_date' => $start_date,
                'end_date' => $end_date,
                'days' => $days,
                'quantity' => $quantity
            ],
            'pricing' => [
                'base_price_per_day' => $base_price_per_day,
                'base_total' => $base_total,
                'adjustments' => $price_adjustments,
                'extras' => $extras_details,
                'subtotal' => $subtotal,
                'platform_commission' => $platform_commission,
                'tax' => $tax,
                'deposit' => $deposit,
                'total' => $total,
                'currency' => CURRENCY_SYMBOL
            ],
            'savings' => [
                'weekly_discount' => isset($price_adjustments[0]) && $price_adjustments[0]['type'] === 'discount' ? $price_adjustments[0]['amount'] : 0,
                'monthly_discount' => $days >= 30 ? ($subtotal * 0.20) : 0,
                'early_bird_discount' => $days_in_advance >= 30 ? $early_bird_discount : 0
            ],
            'vendor' => [
                'name' => $item_data['vendor_name'],
                'rating' => $item_data['rating_average'],
                'response_time' => $item_data['response_time'] ?? 'N/A'
            ]
        ],
        'valid_until' => date('c', strtotime('+15 minutes')), // Quote valid for 15 minutes
        'terms' => [
            'deposit_policy' => 'Security deposit is fully refundable upon return of item in original condition.',
            'cancellation_policy' => 'Free cancellation up to 48 hours before rental start date.',
            'damage_policy' => 'Customer responsible for any damage beyond normal wear and tear.'
        ]
    ];
    
    // Log the calculation (for analytics)
    log_info('Price calculation', [
        'item_id' => $item_id,
        'user_id' => Auth::check() ? Auth::id() : null,
        'days' => $days,
        'quantity' => $quantity,
        'total' => $total,
        'ip' => get_client_ip()
    ]);
    
    echo json_encode($response);
    
} catch (Exception $e) {
    log_error('Price calculation error', $e->getMessage(), [
        'input' => $input,
        'trace' => $e->getTraceAsString()
    ]);
    
    http_response_code(500);
    echo json_encode([
        'error' => 'An error occurred while calculating the price',
        'code' => 'CALC_ERROR'
    ]);
}