<?php
session_start();
require_once '../../config/database.php';
require_once '../../includes/sms_helper.php';

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

// Verify admin access
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    echo json_encode(['error' => 'Access denied']);
    exit;
}

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    // Validate required fields
    if (!isset($input['message_log_id']) || !isset($input['status'])) {
        throw new Exception('Missing required fields: message_log_id and status');
    }
    
    $message_log_id = (int)$input['message_log_id'];
    $status = $input['status'];
    $delivery_report = $input['delivery_report'] ?? null;
    
    // Validate status
    $valid_statuses = ['pending', 'sent', 'delivered', 'failed'];
    if (!in_array($status, $valid_statuses)) {
        throw new Exception('Invalid status. Must be one of: ' . implode(', ', $valid_statuses));
    }
    
    // Update the message delivery status
    $result = update_message_delivery_status($pdo, $message_log_id, $status, $delivery_report);
    
    if ($result) {
        echo json_encode([
            'success' => true,
            'message' => 'Delivery status updated successfully',
            'message_log_id' => $message_log_id,
            'new_status' => $status
        ]);
    } else {
        throw new Exception('Failed to update delivery status');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>