<?php

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


if (!$auth->isSuperAdmin($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_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';


$sessionSql = "SELECT s.*, b.branch_name FROM stock_taking_sessions s
               JOIN branches b ON s.branch_id = b.branch_id
               WHERE s.session_id = :session_id";
$sessionStmt = $conn->prepare($sessionSql);
$sessionStmt->bindValue(':session_id', $sessionId, PDO::PARAM_INT);
$sessionStmt->execute();
$session = $sessionStmt->fetch(PDO::FETCH_ASSOC);


$pendingUpdates = $stockTaking->getPendingUpdateRequests($sessionId);


$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['approve_update'])) {
    $updateId = (int)$_POST['update_id'];
    $result = $stockTaking->approveReportUpdate($updateId, $_SESSION['user_id'], $userRole);

    if ($result) {
        $message = '<div class="alert alert-success">Update request approved successfully!</div>';

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

<style>
    .update-card {
        border: 1px solid #dee2e6;
        border-radius: 8px;
        margin-bottom: 20px;
        transition: box-shadow 0.3s ease;
    }

    .update-card:hover {
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }

    .update-header {
        background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
        border-bottom: 1px solid #dee2e6;
        padding: 15px;
        border-radius: 8px 8px 0 0;
    }

    .approval-status {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 0.8em;
        font-weight: 600;
    }

    .status-pending { background: #fff3cd; color: #856404; }
    .status-approved { background: #d1ecf1; color: #0c5460; }

    .update-details {
        background: #f8f9fa;
        padding: 15px;
        border-radius: 0 0 8px 8px;
    }

    .item-change {
        background: white;
        border: 1px solid #e9ecef;
        border-radius: 5px;
        padding: 8px;
        margin: 5px 0;
    }

    .change-arrow {
        color: #007bff;
        font-weight: bold;
    }
</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">Approve Updates</li>
                </ol>
            </nav>
        </div>
    </div>


    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h2><i class="fas fa-check-double"></i> Approve Report Updates</h2>
                    <p class="mb-0">Review and approve pending update requests for stock taking session</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> Admin approval is required for any update request to be applied.
                            </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; ?>


    <?php if (empty($pendingUpdates)): ?>
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body text-center py-5">
                        <i class="fas fa-check-circle fa-3x text-success mb-3"></i>
                        <h4>No Pending Update Requests</h4>
                        <p class="text-muted">There are currently no update requests waiting for approval.</p>
                        <a href="session_report.php?session_id=<?php echo $sessionId; ?>" class="btn btn-primary">
                            <i class="fas fa-arrow-left"></i> Back to Report
                        </a>
                    </div>
                </div>
            </div>
        </div>
    <?php else: ?>
        <?php foreach ($pendingUpdates as $update): ?>
            <div class="row">
                <div class="col-12">
                    <div class="update-card">
                        <div class="update-header">
                            <div class="row align-items-center">
                                <div class="col-md-6">
                                    <h5 class="mb-1">
                                        <i class="fas fa-edit"></i> Update Request #<?php echo $update['update_id']; ?>
                                    </h5>
                                    <small class="text-muted">
                                        Requested by <?php echo htmlspecialchars($update['requested_by_name']); ?> on
                                        <?php echo date('M j, Y \a\t g:i A', strtotime($update['requested_at'])); ?>
                                    </small>
                                </div>
                                <div class="col-md-6 text-md-end">
                                    <span class="approval-status status-pending">Pending Approval</span>
                                </div>
                            </div>
                        </div>

                        <div class="update-details">
                            <div class="row">
                                <div class="col-md-8">
                                    <h6>Reason for Update:</h6>
                                    <p class="mb-3"><?php echo nl2br(htmlspecialchars($update['update_reason'])); ?></p>

                                    <h6>Proposed Changes:</h6>
                                    <?php
                                    $updateData = json_decode($update['update_data'], true);
                                    if (!empty($updateData)):

                                        $uniqueCodes = array_keys($updateData);
                                        $placeholders = str_repeat('?,', count($uniqueCodes) - 1) . '?';
                                        $itemSql = "SELECT unique_code, item_name, item_details FROM items WHERE unique_code IN ($placeholders)";
                                        $itemStmt = $conn->prepare($itemSql);
                                        $itemStmt->execute($uniqueCodes);
                                        $itemRows = $itemStmt->fetchAll(PDO::FETCH_ASSOC);
                                        $itemNames = [];
                                        $itemDetails = [];
                                        foreach ($itemRows as $itemRow) {
                                            $itemNames[$itemRow['unique_code']] = $itemRow['item_name'];
                                            $itemDetails[$itemRow['unique_code']] = $itemRow['item_details'] ?? '';
                                        }
                                    ?>
                                        <?php foreach ($updateData as $uniqueCode => $newStatus): ?>
                                            <div class="item-change">
                                                <strong><?php echo htmlspecialchars($itemNames[$uniqueCode] ?? 'Unknown Item'); ?></strong>
                                                <br><small class="text-muted">Details: <?php echo htmlspecialchars($itemDetails[$uniqueCode] ?? 'N/A'); ?></small>
                                                <br><small class="text-muted">Code: <?php echo htmlspecialchars($uniqueCode); ?></small>
                                                <span class="change-arrow"> → </span>
                                                <span class="badge bg-warning"><?php echo ucfirst($newStatus); ?></span>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <p class="text-muted">No changes specified</p>
                                    <?php endif; ?>
                                </div>

                                <div class="col-md-4">
                                    <h6>Approval Status:</h6>
                                    <div class="mb-3">
                                        <strong>Admin Approval:</strong>
                                        <?php if ($update['admin_approved_by']): ?>
                                            <span class="badge bg-success">
                                                <i class="fas fa-check"></i> Approved by <?php echo htmlspecialchars($update['admin_approved_name']); ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-warning">
                                                <i class="fas fa-clock"></i> Pending Admin Approval
                                            </span>
                                        <?php endif; ?>
                                    </div>

                                    <?php if ($userRole === 'admin' && !$update['admin_approved_by']): ?>
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="update_id" value="<?php echo $update['update_id']; ?>">
                                            <button type="submit" name="approve_update" class="btn btn-success btn-sm"
                                                    onclick="return confirm('Are you sure you want to approve this update request? This will immediately apply the changes to the report.')">
                                                <i class="fas fa-thumbs-up"></i> Approve & Apply Update
                                            </button>
                                        </form>
                                    <?php elseif ($userRole === 'admin' && $update['admin_approved_by']): ?>
                                        <span class="text-muted small">
                                            <i class="fas fa-check-circle text-success"></i> You have already approved this update
                                        </span>
                                    <?php elseif ($userRole !== 'admin'): ?>
                                        <span class="text-muted small">
                                            <i class="fas fa-info-circle"></i> Only administrators can approve updates
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>


    <div class="row mt-4">
        <div class="col-12 text-center">
            <a href="session_report.php?session_id=<?php echo $sessionId; ?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Report
            </a>
        </div>
    </div>
</div>

<?php include '../../includes/footer.php'; ?>