<?php
require_once '../includes/db_config.php';
session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

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

if (!isset($data['order_id']) || !isset($data['status']) || !isset($data['customer_name']) || 
    !isset($data['customer_phone']) || !isset($data['customer_address']) || !isset($data['total_amount'])) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

try {
    $db = getDBConnection();

    $sql = "UPDATE orders SET 
              status = :status,
              customer_name = :customer_name,
              customer_phone = :customer_phone,
              customer_address = :customer_address,
              total_amount = :total_amount,
              notes = :notes,
              updated_at = NOW()
            WHERE id = :order_id";

    $st = $db->prepare($sql);
    $st->bindParam(':status', $data['status']);
    $st->bindParam(':customer_name', $data['customer_name']);
    $st->bindParam(':customer_phone', $data['customer_phone']);
    $st->bindParam(':customer_address', $data['customer_address']);
    $st->bindParam(':total_amount', $data['total_amount']);
    $st->bindParam(':notes', $data['notes']);
    $st->bindParam(':order_id', $data['order_id'], PDO::PARAM_INT);

    if ($st->execute()) {
        $log = $db->prepare("INSERT INTO order_logs (order_id, action, details, user_id) VALUES (:order_id, 'update', :details, :user_id)");
        $det = 'Order #'.$data['order_id'].' updated. Status changed to: '.$data['status'];
        $log->bindParam(':order_id', $data['order_id'], PDO::PARAM_INT);
        $log->bindParam(':details', $det);
        $log->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
        $log->execute();

        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'message' => 'Order updated successfully']);
    } else {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Failed to update order']);
    }

} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
