<?php

include '../../includes/header.php';


if (!$auth->isSuperAdmin($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_SESSION['user_id']) &&
    !$auth->isBranchManager($_SESSION['user_id']) &&
    !$auth->isAssistant($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit;
}


$sessionId = isset($_GET['session_id']) ? (int)$_GET['session_id'] : 0;
if (!$sessionId) {
    header('Location: stocktaking_dashboard.php');
    exit;
}


$database = new Database();
$conn = $database->getConnection();
require_once __DIR__ . '/../../classes/StockTaking.php';
$stockTaking = new StockTaking($conn);


if (!$auth->isSuperAdmin($_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) {
        header('Location: stocktaking_dashboard.php');
        exit;
    }
}


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


$report = $stockTaking->getSessionReport($sessionId);
if (isset($report['error'])) {
    die("Error: " . $report['error']);
}

$session = $report['session'];


$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_update'])) {
    $reason = trim($_POST['reason'] ?? '');
    $updateData = [];


    if (isset($_POST['item_updates']) && is_array($_POST['item_updates'])) {
        foreach ($_POST['item_updates'] as $uniqueCode => $newStatus) {
            if (!empty($newStatus) && in_array($newStatus, ['found', 'missing', 'extra'])) {
                $updateData[$uniqueCode] = $newStatus;
            }
        }
    }

    if (empty($updateData)) {
        $message = '<div class="alert alert-danger">Please select at least one item to update.</div>';
    } else {
        $result = $stockTaking->requestReportUpdate($sessionId, $_SESSION['user_id'], $reason, $updateData);
        if ($result) {
            $message = '<div class="alert alert-success">Update request submitted successfully! It will be reviewed and approved by an administrator before being applied.</div>';

            header("Refresh: 3; url=session_report.php?session_id=$sessionId");
        } else {
            $message = '<div class="alert alert-danger">Failed to submit update request. Please try again.</div>';
        }
    }
}


$verifications = array_merge($report['found_items'], $report['missing_items'], $report['extra_items']);
?>

<style>
    .update-form {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
    }

    .item-checkbox {
        margin: 5px 0;
        padding: 10px;
        border: 1px solid #dee2e6;
        border-radius: 5px;
        background: white;
    }

    .status-badge {
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 0.75em;
        font-weight: bold;
    }

    .badge-found { background: #d4edda; color: #155724; }
    .badge-missing { background: #f8d7da; color: #721c24; }
    .badge-extra { background: #d1ecf1; color: #0c5460; }
</style>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="stocktaking_dashboard.php">Stock Taking</a></li>
                    <li class="breadcrumb-item"><a href="session_report.php?session_id=<?php echo $sessionId; ?>">Report</a></li>
                    <li class="breadcrumb-item active">Request Update</li>
                </ol>
            </nav>
        </div>
    </div>


    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-warning text-dark">
                    <h2><i class="fas fa-edit"></i> Request Report Update</h2>
                    <p class="mb-0">Update the status of items that were incorrectly recorded during stock taking</p>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <strong>Branch:</strong> <?php echo htmlspecialchars($session['branch_name']); ?><br>
                            <strong>Date:</strong> <?php echo date('F j, Y', strtotime($session['session_date'])); ?><br>
                            <strong>Status:</strong> <span class="badge bg-success">Completed</span>
                        </div>
                        <div class="col-md-6">
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle"></i>
                                <strong>Note:</strong> This update request will be sent to administrators for approval before being applied to the final report.
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php if (!empty($message)): ?>
        <div class="row">
            <div class="col-12">
                <?php echo $message; ?>
            </div>
        </div>
    <?php endif; ?>


    <form method="POST" action="">
        <div class="row">
            <div class="col-12">
                <div class="update-form">

                    <h4>Select Items to Update</h4>
                    <p class="text-muted">Check the items you want to update and select their new status:</p>

                    <div class="row">
                        <?php foreach ($verifications as $item): ?>
                            <div class="col-md-6">
                                <div class="item-checkbox">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox"
                                               name="update_item[<?php echo htmlspecialchars($item['unique_code']); ?>]"
                                               id="item_<?php echo htmlspecialchars($item['unique_code']); ?>"
                                               value="1">
                                        <label class="form-check-label" for="item_<?php echo htmlspecialchars($item['unique_code']); ?>">
                                            <strong><?php echo htmlspecialchars($item['item_name'] ?? 'Unknown Item'); ?></strong><br><small>Details: <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></small>
                                            <br><small class="text-muted">Code: <?php echo htmlspecialchars($item['unique_code']); ?></small>
                                            <br><span class="status-badge badge-<?php echo $item['status']; ?>">
                                                Current: <?php echo ucfirst($item['status']); ?>
                                            </span>
                                        </label>
                                    </div>

                                    <div class="mt-2 ms-4" id="status_<?php echo htmlspecialchars($item['unique_code']); ?>" style="display: none;">
                                        <label class="form-label small">New Status:</label>
                                        <select name="item_updates[<?php echo htmlspecialchars($item['unique_code']); ?>]" class="form-select form-select-sm">
                                            <option value="">Select new status</option>
                                            <option value="found">Found</option>
                                            <option value="missing">Missing</option>
                                            <option value="extra">Extra</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>


        <div class="row">
            <div class="col-12 text-center">
                <a href="session_report.php?session_id=<?php echo $sessionId; ?>" class="btn btn-secondary me-2">
                    <i class="fas fa-arrow-left"></i> Back to Report
                </a>
                <button type="submit" name="request_update" class="btn btn-warning">
                    <i class="fas fa-paper-plane"></i> Submit Update Request
                </button>
            </div>
        </div>
    </form>
</div>

<script>

document.querySelectorAll('input[type="checkbox"]').forEach(function(checkbox) {
    checkbox.addEventListener('change', function() {
        const uniqueCode = this.name.match(/\[([^\]]+)\]/)[1];
        const statusDiv = document.getElementById('status_' + uniqueCode);
        if (this.checked) {
            statusDiv.style.display = 'block';
        } else {
            statusDiv.style.display = 'none';

            const select = statusDiv.querySelector('select');
            if (select) select.value = '';
        }
    });
});
</script>

