<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
date_default_timezone_set("Asia/Kolkata");

include('DB.php');

// --- 1. GLOBAL INPUT HANDLING ---
// Read raw input for JSON requests
$rawInput = file_get_contents('php://input');
$jsonParams = json_decode($rawInput, true);

// Merge $_POST (for standard form submits) and JSON (for fetch/axios)
// JSON takes priority if both exist
$params = is_array($jsonParams) ? array_merge($_POST, $jsonParams) : $_POST;

$action = $params['action'] ?? null;

// --------------------------------
if ($action === 'saveAppointment') {
    $bdd = new DB();
	
	if($params['appointment_user_id']<1 || empty($params['appointment_user_id'])){
		echo json_encode(['status' => 'fail']);
		exit;
	}
    $service_id = $params['appointment_user_id'] ?? 0;
	$service_type = $params['appointment_service_type'] ?? 0;
	$service_date = $params['appointment_date'];
	$time_slot = $params['appointment_time_slot'] ?? 0;
	$user_id = $_SESSION['user_id'] ?? 0;
	
    $rows = $bdd->execute("INSERT INTO `appointment` (`service_id`, `service_type`, `service_date`, `time_slot`, `user_id`) VALUES (?,?,?,?,?)", [$service_id,$service_type,$service_date,$time_slot,$user_id]);
    $bdd->disconnect();
    
	echo json_encode(['status' => 'success','result'=>$params]);
	
    exit;

} else if ($action === 'getAppointmentUserData') {
    $bdd = new DB();
    $service_id = $params['service_id'] ?? 0;
    $rows = $bdd->getOne("SELECT id,product_id, mobile_no, chassis_no, registration_no FROM service WHERE id = ?", [$service_id]);
    $bdd->disconnect();
    
    // FIX: Ensure we always echo something, even if empty
    if(empty($rows)){
        echo json_encode(['status' => 'fail', 'message' => 'No data found '.$service_id]);
    } else {
        echo json_encode(['status' => 'success', 'result' => $rows]);
    }
    
    exit;

} else if ($action === 'load') {
    $bdd = new DB();

    // Use $params instead of $_POST to be safe
    $user_id = isset($params['user_id']) ? (int)$params['user_id'] : 0;
    
    $rows = $bdd->getAll("SELECT * FROM user_permissions WHERE user_id = ?", [$user_id]);

    echo json_encode($rows);
    $bdd->disconnect();
    exit;

} else if ($action === 'save') {
    $bdd = new DB();

    // No need to decode file_get_contents again, we did it at the top
    $user_id = (int)$params['user_id'];
    $permissions = $params['permissions'];

    foreach ($permissions as $perm) {

        $page_key = $perm['page_key'];
        $can_view = (int)$perm['can_view'];
        $can_edit = (int)$perm['can_edit'];
        $can_delete = (int)$perm['can_delete'];
        
        $other_permissions = isset($perm['other_permissions']) ? json_encode($perm['other_permissions']) : null;

        $exists = $bdd->getOne(
            "SELECT id FROM user_permissions WHERE user_id = ? AND page_key = ?",
            [$user_id, $page_key]
        );

        if ($exists) {
            $bdd->execute(
                "UPDATE user_permissions 
                 SET can_view = ?, can_edit = ?, can_delete = ?, other_permissions = ?
                 WHERE user_id = ? AND page_key = ?",
                [$can_view, $can_edit, $can_delete, $other_permissions, $user_id, $page_key]
            );
        } else {
            $bdd->execute(
                "INSERT INTO user_permissions 
                 (user_id, page_key, can_view, can_edit, can_delete, other_permissions)
                 VALUES (?, ?, ?, ?, ?, ?)",
                [$user_id, $page_key, $can_view, $can_edit, $can_delete, $other_permissions]
            );
        }
    }

    echo json_encode(['status' => 'success']);

    $bdd->disconnect();
    exit;
}else {
    // Catch-all for when action is missing or doesn't match
    echo json_encode([
        'status' => 'error', 
        'message' => 'Invalid action provided',
        'debug_received_action' => $action // Helps you see what PHP actually received
    ]);
    exit;
}
?>
