<?php
// actions/toggle_provider_status.php
session_start();
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

include '../layouts/dbconn.php';

// Check if required parameters are provided
if (!isset($_POST['provider_id']) || !isset($_POST['action'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit();
}

$provider_id = intval($_POST['provider_id']);
$action = $_POST['action'];
$user_id = $_SESSION['user_id'];

// Validate action
if (!in_array($action, ['activate', 'deactivate'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit();
}

$conn->begin_transaction();

try {
    // Get provider details
    $get_sql = "SELECT provider_name, provider_code, is_active FROM external_service_providers WHERE provider_id = ?";
    $stmt = $conn->prepare($get_sql);
    $stmt->bind_param('i', $provider_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception('Provider not found');
    }
    
    $provider = $result->fetch_assoc();
    
    // Check if action is valid
    if ($action === 'activate' && $provider['is_active'] == 1) {
        throw new Exception('Provider is already active');
    }
    if ($action === 'deactivate' && $provider['is_active'] == 0) {
        throw new Exception('Provider is already inactive');
    }
    
    // Update provider status
    $new_status = ($action === 'activate') ? 1 : 0;
    $update_sql = "UPDATE external_service_providers SET is_active = ?, updated_at = CURRENT_TIMESTAMP WHERE provider_id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param('ii', $new_status, $provider_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update provider status');
    }
    
    // Log activity
    $activity_sql = "INSERT INTO activity_logs (user_id, action, description, ip_address) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $log_action = strtoupper($action) . '_PROVIDER';
    $description = ucfirst($action) . "d external service provider: {$provider['provider_name']} ({$provider['provider_code']})";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt->bind_param('isss', $user_id, $log_action, $description, $ip_address);
    $stmt->execute();
    
    $conn->commit();
    
    $message = "Provider " . ($action === 'activate' ? 'activated' : 'deactivated') . " successfully!";
    echo json_encode(['success' => true, 'message' => $message]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

$conn->close();
?>