<?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 approve an import.';
    header('Location: import.php');
    exit();
}

// Check role permissions - managers and admins can approve
$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 approve 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'];

// Check if this is a POST request (form submission)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // User has approved the import
    $isApproved = isset($_POST['approve']) && $_POST['approve'] === '1';
    
    if ($isApproved) {
        // Update batch status to approved
        $updateStmt = $conn->prepare("
            UPDATE import_batches 
            SET status = 'approved', processed_by = ?, processed_at = NOW() 
            WHERE batch_id = ?
        ");
        
        $updateStmt->bind_param("ii", $userId, $batchId);
        
        if ($updateStmt->execute()) {
            $_SESSION['success_message'] = 'Import batch approved successfully.';
            header('Location: process_import.php?id=' . $batchId);
            exit();
        } else {
            $_SESSION['error_message'] = 'Error approving import batch: ' . $conn->error;
            header('Location: import.php');
            exit();
        }
    } else {
        // Update batch status to rejected
        $rejectReason = $_POST['reject_reason'] ?? '';
        
        $updateStmt = $conn->prepare("
            UPDATE import_batches 
            SET status = 'rejected', processed_by = ?, processed_at = NOW() 
            WHERE batch_id = ?
        ");
        
        $updateStmt->bind_param("ii", $userId, $batchId);
        
        if ($updateStmt->execute()) {
            $_SESSION['success_message'] = 'Import batch rejected.';
            header('Location: import.php');
            exit();
        } else {
            $_SESSION['error_message'] = 'Error rejecting import batch: ' . $conn->error;
            header('Location: import.php');
            exit();
        }
    }
}

// Fetch batch information
$batchStmt = $conn->prepare("
    SELECT ib.*, 
           u.full_name as created_by_name 
    FROM import_batches ib
    JOIN users u ON ib.created_by = u.user_id
    WHERE ib.batch_id = ?
");

$batchStmt->bind_param("i", $batchId);
$batchStmt->execute();
$batchResult = $batchStmt->get_result();

if ($batchResult->num_rows === 0) {
    $_SESSION['error_message'] = 'Batch not found.';
    header('Location: import.php');
    exit();
}

$batchInfo = $batchResult->fetch_assoc();

// Get records validation summary
$validationSummaryStmt = $conn->prepare("
    SELECT 
        SUM(CASE WHEN status = 'valid' THEN 1 ELSE 0 END) as valid_count,
        SUM(CASE WHEN status = 'invalid' THEN 1 ELSE 0 END) as invalid_count,
        COUNT(*) as total_count
    FROM import_records
    WHERE batch_id = ?
");

$validationSummaryStmt->bind_param("i", $batchId);
$validationSummaryStmt->execute();
$summaryResult = $validationSummaryStmt->get_result();
$summary = $summaryResult->fetch_assoc();

// Get sample of valid and invalid records
$recordsStmt = $conn->prepare("
    SELECT *
    FROM import_records
    WHERE batch_id = ?
    ORDER BY CASE WHEN status = 'invalid' THEN 0 ELSE 1 END, row_index
    LIMIT 20
");

$recordsStmt->bind_param("i", $batchId);
$recordsStmt->execute();
$recordsResult = $recordsStmt->get_result();

$records = [];
while ($row = $recordsResult->fetch_assoc()) {
    $records[] = $row;
}

// Include the page header
include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Approve Import')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .validation-summary {
            font-size: 1.1rem;
            margin-bottom: 2rem;
        }
        
        .validation-summary .badge {
            font-size: 1rem;
            padding: 0.5rem 0.75rem;
        }
        
        .record-card {
            margin-bottom: 1.5rem;
        }
        
        .record-preview {
            max-height: 200px;
            overflow-y: auto;
        }
        
        .invalid-badge {
            position: absolute;
            top: 0;
            right: 0;
            margin: 10px;
        }
        
        pre {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Import Management', 'title' => 'Approve Import Batch')); ?>

                    <!-- Display notifications -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h4 class="card-title mb-0 flex-grow-1">Import Batch Details</h4>
                                    <div>
                                        <a href="import.php" class="btn btn-light btn-sm">
                                            <i class="ri-arrow-left-line align-middle"></i> Back to Imports
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <table class="table table-sm">
                                                <tr>
                                                    <th>Batch ID:</th>
                                                    <td>#<?php echo $batchInfo['batch_id']; ?></td>
                                                </tr>
                                                <tr>
                                                    <th>Filename:</th>
                                                    <td><?php echo htmlspecialchars($batchInfo['filename']); ?></td>
                                                </tr>
                                                <tr>
                                                    <th>Import Type:</th>
                                                    <td>
                                                        <?php 
                                                        $typeName = ($batchInfo['import_type'] == 'transit_shipment') 
                                                            ? 'Transit Shipment' 
                                                            : 'Local Shipment';
                                                        echo $typeName;
                                                        ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <th>Created By:</th>
                                                    <td><?php echo htmlspecialchars($batchInfo['created_by_name']); ?></td>
                                                </tr>
                                                <tr>
                                                    <th>Created At:</th>
                                                    <td><?php echo date('M d, Y h:i A', strtotime($batchInfo['created_at'])); ?></td>
                                                </tr>
                                            </table>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="validation-summary">
                                                <div class="d-flex justify-content-between align-items-center mb-2">
                                                    <span>Total Records:</span>
                                                    <span class="badge bg-info"><?php echo $summary['total_count']; ?></span>
                                                </div>
                                                <div class="d-flex justify-content-between align-items-center mb-2">
                                                    <span>Valid Records:</span>
                                                    <span class="badge bg-success"><?php echo $summary['valid_count']; ?></span>
                                                </div>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <span>Invalid Records:</span>
                                                    <span class="badge bg-danger"><?php echo $summary['invalid_count']; ?></span>
                                                </div>
                                            </div>
                                            
                                            <?php if ($batchInfo['status'] === 'pending'): ?>
                                                <form method="post" action="">
                                                    <div class="mt-4">
                                                        <h5>Approval Action</h5>
                                                        <div class="form-check mb-3">
                                                            <input class="form-check-input" type="radio" name="approve" id="approveYes" value="1" checked>
                                                            <label class="form-check-label" for="approveYes">
                                                                Approve and Process Import
                                                            </label>
                                                        </div>
                                                        <div class="form-check mb-3">
                                                            <input class="form-check-input" type="radio" name="approve" id="approveNo" value="0">
                                                            <label class="form-check-label" for="approveNo">
                                                                Reject Import
                                                            </label>
                                                        </div>
                                                        <div id="rejectReasonDiv" class="mb-3" style="display: none;">
                                                            <label for="reject_reason" class="form-label">Reason for Rejection:</label>
                                                            <textarea class="form-control" id="reject_reason" name="reject_reason" rows="3"></textarea>
                                                        </div>
                                                        <div class="mt-3">
                                                            <button type="submit" class="btn btn-primary">Submit Decision</button>
                                                        </div>
                                                    </div>
                                                </form>
                                            <?php else: ?>
                                                <div class="alert alert-info mt-4">
                                                    This import batch has already been <?php echo $batchInfo['status']; ?>.
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Record Preview Section -->
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Record Preview</h4>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <?php foreach ($records as $record): 
                                            $recordData = json_decode($record['record_data'], true);
                                            $validationErrors = json_decode($record['validation_errors'], true);
                                            $isValid = $record['status'] === 'valid';
                                        ?>
                                            <div class="col-md-6">
                                                <div class="card record-card">
                                                    <?php if (!$isValid): ?>
                                                        <span class="badge bg-danger invalid-badge">Invalid</span>
                                                    <?php endif; ?>
                                                    <div class="card-header">
                                                        <h5 class="card-title mb-0">
                                                            Record #<?php echo $record['row_index']; ?>
                                                            <?php if (!empty($record['generated_file_number'])): ?>
                                                                <span class="badge bg-success ms-2">
                                                                    <?php echo $record['generated_file_number']; ?>
                                                                </span>
                                                            <?php endif; ?>
                                                        </h5>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="record-preview">
                                                            <pre><?php echo json_encode($recordData, JSON_PRETTY_PRINT); ?></pre>
                                                        </div>
                                                        
                                                        <?php if (!$isValid && is_array($validationErrors) && !empty($validationErrors)): ?>
                                                            <div class="mt-3">
                                                                <h6 class="text-danger">Validation Errors:</h6>
                                                                <ul class="text-danger">
                                                                    <?php foreach ($validationErrors as $error): ?>
                                                                        <li><?php echo htmlspecialchars($error); ?></li>
                                                                    <?php endforeach; ?>
                                                                </ul>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Toggle reject reason textarea visibility
            const approveRadios = document.querySelectorAll('input[name="approve"]');
            const rejectReasonDiv = document.getElementById('rejectReasonDiv');
            
            approveRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    if (this.value === '0') { // Reject
                        rejectReasonDiv.style.display = 'block';
                    } else {
                        rejectReasonDiv.style.display = 'none';
                    }
                });
            });
        });
    </script>
</body>
</html>