<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    $_SESSION['error_message'] = 'You must be logged in to reject an import.';
    header('Location: import.php');
    exit();
}

// Check role permissions - managers and admins can reject
$role_id = $_SESSION['role_id'] ?? 0;
$allowed_roles = [1, 2, 3]; // Admin, General Manager, Operations
if (!in_array($role_id, $allowed_roles)) {
    $_SESSION['error_message'] = 'You do not have permission to reject imports.';
    header('Location: import.php');
    exit();
}

// Check if batch ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_message'] = 'Invalid batch ID.';
    header('Location: import.php');
    exit();
}

$batchId = intval($_GET['id']);
$userId = $_SESSION['user_id'];

// Get the reason if provided
$reason = $_POST['reason'] ?? '';

// Update batch status to rejected
$updateStmt = $conn->prepare("
    UPDATE import_batches 
    SET status = 'rejected', processed_by = ?, processed_at = NOW() 
    WHERE batch_id = ? AND status = 'pending'
");

$updateStmt->bind_param("ii", $userId, $batchId);

if ($updateStmt->execute() && $updateStmt->affected_rows > 0) {
    $_SESSION['success_message'] = 'Import batch rejected successfully.';
} else {
    $_SESSION['error_message'] = 'Error rejecting import batch or batch is not in pending status.';
}

header('Location: import.php');
exit();
?>