<?PHP
error_log("Stock Taking: record_verification.php called");
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("Stock Taking: User role check failed for user_id: " . ($_SESSION['user_id'] ?? 'none'));
    error_log("Stock Taking: Session data: " . json_encode($_SESSION));
    error_log("Stock Taking: Auth checks - SuperAdmin: " . ($auth->isSuperAdmin($_SESSION['user_id'] ?? 0) ? 'YES' : 'NO'));
    error_log("Stock Taking: Auth checks - Warehouse: " . ($auth->isWarehousePersonnel($_SESSION['user_id'] ?? 0) ? 'YES' : 'NO'));
    error_log("Stock Taking: Auth checks - BranchManager: " . ($auth->isBranchManager($_SESSION['user_id'] ?? 0) ? 'YES' : 'NO'));
    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("Stock Taking: Session check failed - user_id not set");
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Session expired - Please login again']);
    exit;
}


$userRole = 'unknown';
if ($auth->isSuperAdmin($_SESSION['user_id'])) {
    $userRole = 'super_admin';
} elseif ($auth->isWarehousePersonnel($_SESSION['user_id'])) {
    $userRole = 'warehouse';
} elseif ($auth->isBranchManager($_SESSION['user_id'])) {
    $userRole = 'branch_manager';
}
error_log("Stock Taking: User authenticated - ID: {$_SESSION['user_id']}, Role: $userRole");


$sessionId = isset($_POST['session_id']) ? (int)$_POST['session_id'] : 0;
$itemId = isset($_POST['item_id']) ? (int)$_POST['item_id'] : 0;
$uniqueCode = trim($_POST['unique_code'] ?? '');
$status = $_POST['status'] ?? '';

error_log("Stock Taking: POST data - session_id: $sessionId, item_id: $itemId, unique_code: $uniqueCode, status: $status");

if (!$sessionId || !$itemId || empty($uniqueCode) || !in_array($status, ['found', 'missing'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid request data']);
    exit;
}

try {

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


    $tables = ['stock_taking_sessions', 'stock_taking_verifications'];
    foreach ($tables as $table) {
        $checkTable = $conn->query("SHOW TABLES LIKE '$table'");
        if ($checkTable->rowCount() == 0) {
            throw new Exception("Required table '$table' does not exist. Please run the stock taking table creation script.");
        }
    }


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


    if ($auth->isBranchManager($_SESSION['user_id'])) {
        $userBranch = $auth->getUserBranch($_SESSION['user_id']);
        $sessionSql = "SELECT branch_id 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 || $session['branch_id'] != $userBranch) {
            throw new Exception("You can only verify items for your own branch.");
        }
    }


    error_log("Record Verification: About to call recordVerification with session: $sessionId, item: $itemId, code: $uniqueCode, status: $status, user: {$_SESSION['user_id']}");
    $result = $stockTaking->recordVerification($sessionId, $itemId, $uniqueCode, $status, $_SESSION['user_id']);
    error_log("Record Verification: recordVerification returned: " . ($result ? 'TRUE' : 'FALSE'));

    if ($result) {

        $sessionData = $stockTaking->getSessionItems($sessionId);

        if (isset($sessionData['error'])) {
            echo json_encode(['success' => false, 'message' => 'Verification recorded but failed to refresh data']);
        } else {
            echo json_encode([
                'success' => true,
                'message' => 'Verification recorded successfully',
                'data' => [
                    'total_items' => $sessionData['total_items'],
                    'verified_items' => $sessionData['verified_items'],
                    'progress_percent' => $sessionData['total_items'] > 0 ?
                        round(($sessionData['verified_items'] / $sessionData['total_items']) * 100, 1) : 0
                ]
            ]);
        }
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to record verification']);
    }
} catch (Exception $e) {
    error_log("Stock Taking: Exception in record_verification.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}
?>