<?php


error_log("Cancel Session: Request received");

header('Content-Type: application/json');


if (session_status() == PHP_SESSION_NONE) {
    session_start();
}


require_once '../../classes/Database.php';
require_once '../../includes/auth.php';

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);


if (!$auth->isSuperAdmin($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_SESSION['user_id']) &&
    !$auth->isBranchManager($_SESSION['user_id'])) {
    error_log("Cancel Session: User role check failed for user_id: " . ($_SESSION['user_id'] ?? 'none'));
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized - Invalid user role']);
    exit;
}


if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    error_log("Cancel Session: Session check failed - user_id not set");
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Session expired - Please login again']);
    exit;
}


$sessionId = isset($_POST['session_id']) ? (int)$_POST['session_id'] : 0;
$action = $_POST['action'] ?? '';

error_log("Cancel Session: POST data - session_id: $sessionId, action: $action");

if (!$sessionId || $action !== 'cancel_session') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid request data']);
    exit;
}

try {

    if (!$conn) {
        throw new Exception("Database connection failed");
    }


    require_once '../../classes/StockTaking.php';
    $stockTaking = new StockTaking($conn);


    $userRole = $auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id'])
        ? 'admin' : 'branch_manager';


    if ($userRole === 'branch_manager') {
        $userBranch = $auth->getUserBranch($_SESSION['user_id']);
        $sessionSql = "SELECT branch_id, session_status FROM stock_taking_sessions WHERE session_id = :session_id";
        $sessionStmt = $conn->prepare($sessionSql);
        $sessionStmt->bindValue(':session_id', $sessionId, PDO::PARAM_INT);
        $sessionStmt->execute();
        $session = $sessionStmt->fetch(PDO::FETCH_ASSOC);

        if (!$session) {
            throw new Exception("Session not found");
        }

        if ($session['branch_id'] != $userBranch) {
            throw new Exception("You can only cancel sessions for your own branch");
        }


        if (!in_array($session['session_status'], ['pending_start', 'in_progress', 'pending_preview', 'pending_verification'])) {
            throw new Exception("This session cannot be cancelled (current status: {$session['session_status']})");
        }
    }


    $result = $stockTaking->cancelSession($sessionId);

    if ($result) {
        error_log("Cancel Session: Session $sessionId cancelled successfully");
        echo json_encode([
            'success' => true,
            'message' => 'Session cancelled successfully'
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to cancel session']);
    }
} catch (Exception $e) {
    error_log("Cancel Session: Exception - " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}
?>