<?php

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


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


if (!$stockTaking->canUserPerformAction($sessionId, $_SESSION['user_id'], $userRole, 'verify')) {
    echo '<div class="alert alert-warning">You cannot verify this session at this time.</div>';
    include '../../includes/footer.php';
    exit;
}


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

$session = $status['session'];


$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_verification'])) {
    $result = $stockTaking->verifySessionCompletion($sessionId, $_SESSION['user_id'], $userRole);
    if ($result) {
        $message = '<div class="alert alert-success">Verification completed successfully! The session has been finalized.</div>';

        header("Refresh: 3; url=stocktaking_dashboard.php");
    } else {
        $message = '<div class="alert alert-danger">Failed to complete verification. Please try again.</div>';
    }
}
?>

<style>
    .verification-header {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        color: white;
        padding: 30px;
        border-radius: 8px;
        margin-bottom: 30px;
    }

    .participant-status {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
    }

    .participant-card {
        border: 2px solid #e9ecef;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
        transition: all 0.3s ease;
    }

    .participant-started {
        border-color: #ffc107;
        background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
    }

    .participant-previewed {
        border-color: #17a2b8;
        background: linear-gradient(135deg, #d1ecf1 0%, #bee5eb 100%);
    }

    .participant-verified {
        border-color: #28a745;
        background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
    }

    .participant-pending {
        border-color: #6c757d;
        background: #f8f9fa;
    }

    .status-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2em;
        margin-right: 15px;
    }

    .icon-started { background: #ffc107; color: white; }
    .icon-previewed { background: #17a2b8; color: white; }
    .icon-verified { background: #28a745; color: white; }
    .icon-pending { background: #6c757d; color: white; }

    .verification-summary {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-radius: 8px;
        padding: 25px;
        margin-bottom: 20px;
    }

    .summary-stat {
        text-align: center;
        padding: 15px;
        border-radius: 6px;
        margin-bottom: 10px;
    }

    .stat-found { background: #d4edda; border: 1px solid #c3e6cb; }
    .stat-missing { background: #f8d7da; border: 1px solid #f5c6cb; }
    .stat-extra { background: #d1ecf1; border: 1px solid #bee5eb; }

    .confirmation-section {
        background: #fff3cd;
        border: 2px solid #ffeaa7;
        border-radius: 8px;
        padding: 25px;
        margin-top: 20px;
    }
</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="preview_session.php?session_id=<?php echo $sessionId; ?>">Preview</a></li>
                    <li class="breadcrumb-item active">Verify Completion</li>
                </ol>
            </nav>
        </div>
    </div>


    <div class="row">
        <div class="col-12">
            <div class="verification-header">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h2><i class="fas fa-check-double"></i> Verify Stock Taking Completion</h2>
                        <p class="mb-2">
                            <strong>Branch:</strong> <?php echo htmlspecialchars($session['branch_name']); ?> |
                            <strong>Date:</strong> <?php echo date('F j, Y', strtotime($session['session_date'])); ?>
                        </p>
                        <p class="mb-0">
                            Please review and confirm the final verification of this stock taking session.
                        </p>
                    </div>
                    <div class="col-md-4 text-md-end">
                        <div class="btn-group">
                            <a href="preview_session.php?session_id=<?php echo $sessionId; ?>" class="btn btn-light">
                                <i class="fas fa-arrow-left"></i> Back to Preview
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

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


    <div class="row mb-4">
        <div class="col-12">
            <div class="participant-status">
                <h5><i class="fas fa-users"></i> Verification Progress</h5>
                <p class="text-muted">Both admin and branch manager must verify to complete the session.</p>

                <div class="row">

                    <div class="col-md-6">
                        <div class="participant-card <?php
                            if ($session['admin_verified_at']) echo 'participant-verified';
                            elseif ($session['admin_preview_at']) echo 'participant-previewed';
                            elseif ($session['admin_started_by']) echo 'participant-started';
                            else echo 'participant-pending';
                        ?>">
                            <div class="d-flex align-items-center">
                                <div class="status-icon <?php
                                    if ($session['admin_verified_at']) echo 'icon-verified';
                                    elseif ($session['admin_preview_at']) echo 'icon-previewed';
                                    elseif ($session['admin_started_by']) echo 'icon-started';
                                    else echo 'icon-pending';
                                ?>">
                                    <?php if ($session['admin_verified_at']): ?>
                                        <i class="fas fa-check-circle"></i>
                                    <?php elseif ($session['admin_preview_at']): ?>
                                        <i class="fas fa-eye"></i>
                                    <?php elseif ($session['admin_started_by']): ?>
                                        <i class="fas fa-play"></i>
                                    <?php else: ?>
                                        <i class="fas fa-clock"></i>
                                    <?php endif; ?>
                                </div>
                                <div>
                                    <h6 class="mb-1">Admin Role</h6>
                                    <p class="mb-0 small">
                                        <?php if ($session['admin_started_by']): ?>
                                            Started by <?php echo htmlspecialchars($session['admin_started_name']); ?>
                                            <?php if ($session['admin_started_at']): ?>
                                                <br><small><?php echo date('M j, Y H:i', strtotime($session['admin_started_at'])); ?></small>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            Not started
                                        <?php endif; ?>
                                    </p>
                                    <?php if ($session['admin_preview_at']): ?>
                                        <p class="mb-0 small text-info">
                                            Previewed: <?php echo date('M j, Y H:i', strtotime($session['admin_preview_at'])); ?>
                                        </p>
                                    <?php endif; ?>
                                    <?php if ($session['admin_verified_at']): ?>
                                        <p class="mb-0 small text-success">
                                            Verified: <?php echo date('M j, Y H:i', strtotime($session['admin_verified_at'])); ?>
                                        </p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>


                    <div class="col-md-6">
                        <div class="participant-card <?php
                            if ($session['branch_verified_at']) echo 'participant-verified';
                            elseif ($session['branch_preview_at']) echo 'participant-previewed';
                            elseif ($session['branch_started_by']) echo 'participant-started';
                            else echo 'participant-pending';
                        ?>">
                            <div class="d-flex align-items-center">
                                <div class="status-icon <?php
                                    if ($session['branch_verified_at']) echo 'icon-verified';
                                    elseif ($session['branch_preview_at']) echo 'icon-previewed';
                                    elseif ($session['branch_started_by']) echo 'icon-started';
                                    else echo 'icon-pending';
                                ?>">
                                    <?php if ($session['branch_verified_at']): ?>
                                        <i class="fas fa-check-circle"></i>
                                    <?php elseif ($session['branch_preview_at']): ?>
                                        <i class="fas fa-eye"></i>
                                    <?php elseif ($session['branch_started_by']): ?>
                                        <i class="fas fa-play"></i>
                                    <?php else: ?>
                                        <i class="fas fa-clock"></i>
                                    <?php endif; ?>
                                </div>
                                <div>
                                    <h6 class="mb-1">Branch Manager Role</h6>
                                    <p class="mb-0 small">
                                        <?php if ($session['branch_started_by']): ?>
                                            Started by <?php echo htmlspecialchars($session['branch_started_name']); ?>
                                            <?php if ($session['branch_started_at']): ?>
                                                <br><small><?php echo date('M j, Y H:i', strtotime($session['branch_started_at'])); ?></small>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            Not started
                                        <?php endif; ?>
                                    </p>
                                    <?php if ($session['branch_preview_at']): ?>
                                        <p class="mb-0 small text-info">
                                            Previewed: <?php echo date('M j, Y H:i', strtotime($session['branch_preview_at'])); ?>
                                        </p>
                                    <?php endif; ?>
                                    <?php if ($session['branch_verified_at']): ?>
                                        <p class="mb-0 small text-success">
                                            Verified: <?php echo date('M j, Y H:i', strtotime($session['branch_verified_at'])); ?>
                                        </p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div class="row mb-4">
        <div class="col-12">
            <div class="verification-summary">
                <h5><i class="fas fa-chart-bar"></i> Session Summary</h5>
                <div class="row text-center mt-3">
                    <div class="col-md-3">
                        <div class="summary-stat stat-found">
                            <h4 class="text-success mb-1"><?php echo $session['total_found_items'] ?? 0; ?></h4>
                            <small class="text-muted">Items Found</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-stat stat-missing">
                            <h4 class="text-danger mb-1"><?php echo $session['total_missing_items'] ?? 0; ?></h4>
                            <small class="text-muted">Items Missing</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-stat stat-extra">
                            <h4 class="text-info mb-1"><?php echo $session['total_extra_items'] ?? 0; ?></h4>
                            <small class="text-muted">Extra Items</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-stat">
                            <h4 class="text-primary mb-1"><?php echo $session['total_system_items'] ?? 0; ?></h4>
                            <small class="text-muted">System Total</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <?php if ($status['can_verify'][$userRole]): ?>
    <div class="row">
        <div class="col-12">
            <div class="confirmation-section">
                <div class="text-center">
                    <h5><i class="fas fa-exclamation-triangle text-warning"></i> Final Verification Required</h5>
                    <p class="mb-4">
                        You are about to verify and finalize this stock taking session.
                        This action cannot be undone and will complete the session for both participants.
                    </p>

                    <div class="row justify-content-center">
                        <div class="col-md-6">
                            <div class="card border-warning">
                                <div class="card-body">
                                    <h6>By confirming verification, you acknowledge:</h6>
                                    <ul class="text-start mb-3">
                                        <li>You have reviewed all verification results</li>
                                        <li>The session data is accurate and complete</li>
                                        <li>This will finalize the stock taking session</li>
                                        <li>Both admin and branch manager verifications are required</li>
                                    </ul>

                                    <form method="POST">
                                        <button type="submit" name="confirm_verification"
                                                class="btn btn-success btn-lg w-100"
                                                onclick="return confirm('Are you sure you want to verify and finalize this stock taking session? This action cannot be undone.')">
                                            <i class="fas fa-check-double"></i> Verify & Finalize Session
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php else: ?>
    <div class="row">
        <div class="col-12">
            <div class="alert alert-info text-center">
                <h5><i class="fas fa-info-circle"></i> Verification Status</h5>
                <p class="mb-0">
                    <?php if ($status['is_complete']): ?>
                        This session has been completed and verified by both participants.
                    <?php elseif (!$status['can_verify'][$userRole]): ?>
                        You have already verified this session or it is not ready for verification.
                    <?php endif; ?>
                </p>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

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