<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

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

try {
    if (!User::isLoggedIn()) { throw new Exception('User not logged in'); }
    if (!User::isAdmin())    { throw new Exception('Access denied'); }

    $in = json_decode(file_get_contents('php://input'), true);
    if (!$in) { throw new Exception('Invalid JSON data'); }

    $oid = isset($in['order_id']) ? (int)$in['order_id'] : 0;
    $st  = isset($in['status']) ? trim($in['status']) : '';
    if (!$oid) { throw new Exception('Order ID is required'); }
    if (!$st)  { throw new Exception('Status is required'); }

    $ok = ['pending','processing','ready','delivered','cancelled'];
    if (!in_array($st, $ok)) { throw new Exception('Invalid status value'); }

    $db = getDBConnection();
    
    $checkQuery = "
        SELECT MAX(CASE WHEN s.category = 'subscription' THEN 1 ELSE 0 END) as is_subscription
        FROM orders o
        LEFT JOIN order_items oi ON o.id = oi.order_id
        LEFT JOIN services s ON oi.service_id = s.id
        WHERE o.id = ?
        GROUP BY o.id
    ";
    $checkStmt = $db->prepare($checkQuery);
    $checkStmt->execute([$oid]);
    $orderCheck = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($orderCheck && $orderCheck['is_subscription'] == 1) {
        throw new Exception('Cannot update subscription orders - they are auto-activated');
    }
    
    $q = "UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?";
    $stp = $db->prepare($q);
    $res = $stp->execute([$st, $oid]);
    if (!$res) { throw new Exception('Failed to update order status'); }
    if ($stp->rowCount() === 0) { throw new Exception('Order not found'); }

    echo json_encode(['success'=>true,'message'=>'Order status updated successfully']);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>$e->getMessage()]);
}
?>
