<?php

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Sales.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}


$userBranchId = null;


if (isset($_SESSION['branch_id'])) {
    $userBranchId = $_SESSION['branch_id'];
} elseif (isset($_SESSION['user_branch_id'])) {
    $userBranchId = $_SESSION['user_branch_id'];
} elseif (isset($_SESSION['branch'])) {
    $userBranchId = $_SESSION['branch'];
} else {

    $sql = "SELECT branch_id FROM users WHERE user_id = :user_id";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && $user['branch_id']) {
        $userBranchId = $user['branch_id'];

        $_SESSION['branch_id'] = $userBranchId;
    }
}


$userRole = $_SESSION['role'] ?? null;
if ($userRole !== 'branch') {
    header('Location: ../../unauthorized.php');
    exit();
}


if (!$userBranchId) {
    header('Location: ../../unauthorized.php');
    exit();
}


$branch = new Branch($conn);
$sales = new Sales($conn);


$branchDetails = $branch->getBranchById($userBranchId);
if (!$branchDetails) {
    header('Location: ../../unauthorized.php');
    exit();
}





$reports = [];
$sql = "SELECT wr.*, b.branch_name, u.username as verified_by_name
        FROM weekly_reports wr
        JOIN branches b ON wr.branch_id = b.branch_id
        LEFT JOIN users u ON wr.verified_by = u.user_id
        WHERE wr.branch_id = :branch_id
        ORDER BY wr.week_start_date DESC";

$stmt = $conn->prepare($sql);
$stmt->bindParam(':branch_id', $userBranchId, PDO::PARAM_INT);
$stmt->execute();
$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);


$reportTotals = [];
foreach ($reports as $report) {
    $weekStart = $report['week_start_date'];
    $weekEnd = date('Y-m-d', strtotime($weekStart . ' +6 days'));


    $sql = "SELECT SUM(total_price) as total_sales
            FROM sold_items
            WHERE branch_id = :branch_id
            AND DATE(sold_at) BETWEEN :start_date AND :end_date";

    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':branch_id', $report['branch_id'], PDO::PARAM_INT);
    $stmt->bindParam(':start_date', $weekStart);
    $stmt->bindParam(':end_date', $weekEnd);
    $stmt->execute();

    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $reportTotals[$report['report_id']] = $result['total_sales'] ?: 0;
}


$pendingReports = array_filter($reports, function($report) {
    return $report['verification_status'] === 'pending';
});

$verifiedReports = array_filter($reports, function($report) {
    return $report['verification_status'] === 'verified';
});


$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
$filteredReports = $reports;

if ($filter === 'pending') {
    $filteredReports = $pendingReports;
} elseif ($filter === 'verified') {
    $filteredReports = $verifiedReports;
}
?>

<?php include '../../includes/header.php'; ?>
    <style>
        .report-table {
            margin-top: 20px;
        }
        .report-row {
            cursor: pointer;
        }
        .report-row:hover {
            background-color: #f5f5f5;
        }
        .status-badge {
            font-size: 0.8rem;
            padding: 0.25rem 0.5rem;
            border-radius: 20px;
        }
        .back-btn {
            margin-bottom: 20px;
        }
        .no-reports {
            text-align: center;
            padding: 50px;
            color: #6c757d;
        }
        .filter-buttons {
            margin-bottom: 20px;
        }
        .filter-buttons .btn {
            margin-right: 10px;
            margin-bottom: 10px;
        }
        .summary-cards {
            margin-bottom: 30px;
        }
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
        }
        .summary-card h4 {
            margin: 0;
            font-size: 2rem;
        }
        .summary-card p {
            margin: 5px 0 0 0;
            opacity: 0.9;
        }
    </style>

    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <a href="../branch/branch.php" class="btn btn-secondary back-btn">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </a>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-12">
                <h2><i class="fas fa-history"></i> <?php echo htmlspecialchars($branchDetails['branch_name']); ?> - Historical Reports</h2>
                <p class="text-muted">View all submitted weekly sales reports for your branch</p>
            </div>
        </div>


        <div class="row summary-cards">
            <div class="col-md-4">
                <div class="summary-card">
                    <h4><?php echo count($reports); ?></h4>
                    <p>Total Reports</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="summary-card" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%); color: #333;">
                    <h4><?php echo count($pendingReports); ?></h4>
                    <p>Pending Verification</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="summary-card" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); color: #333;">
                    <h4><?php echo count($verifiedReports); ?></h4>
                    <p>Verified Reports</p>
                </div>
            </div>
        </div>


        <div class="filter-buttons">
            <a href="?filter=all" class="btn <?php echo $filter === 'all' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                <i class="fas fa-list"></i> All Reports (<?php echo count($reports); ?>)
            </a>
            <a href="?filter=pending" class="btn <?php echo $filter === 'pending' ? 'btn-warning' : 'btn-outline-warning'; ?>">
                <i class="fas fa-clock"></i> Pending Verification (<?php echo count($pendingReports); ?>)
            </a>
            <a href="?filter=verified" class="btn <?php echo $filter === 'verified' ? 'btn-success' : 'btn-outline-success'; ?>">
                <i class="fas fa-check-circle"></i> Verified (<?php echo count($verifiedReports); ?>)
            </a>
        </div>

        <?php if (empty($filteredReports)): ?>
            <div class="no-reports">
                <i class="fas fa-file-alt fa-3x mb-3"></i>
                <h4>No reports found</h4>
                <p>
                    <?php if ($filter === 'pending'): ?>
                        No pending reports found for your branch.
                    <?php elseif ($filter === 'verified'): ?>
                        No verified reports found for your branch.
                    <?php else: ?>
                        No reports have been submitted for your branch yet.
                    <?php endif; ?>
                </p>
                <?php if (empty($reports)): ?>
                    <a href="../sales/weekly2.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Submit Your First Report
                    </a>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="table-responsive report-table">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Week Period</th>
                            <th>Total Sales</th>
                            <th>Submitted Date</th>
                            <th>Status</th>
                            <th>Verified On</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($filteredReports as $report): ?>
                        <tr class="report-row" onclick="window.location='../views/reports/view_report.php?report_id=<?php echo $report['report_id']; ?>'">
                            <td>
                                <strong>
                                    <?php echo date('M d', strtotime($report['week_start_date'])); ?> -
                                    <?php echo date('M d, Y', strtotime($report['week_start_date'] . ' +6 days')); ?>
                                </strong>
                                <br>
                                <small class="text-muted">
                                    Week of <?php echo date('Y', strtotime($report['week_start_date'])); ?>
                                </small>
                            </td>
                            <td>
                                <strong>MWK <?php echo number_format($reportTotals[$report['report_id']], 2); ?></strong>
                            </td>
                            <td>
                                <?php echo date('M d, Y', strtotime($report['created_at'])); ?>
                                <br>
                                <small class="text-muted"><?php echo date('g:i A', strtotime($report['created_at'])); ?></small>
                            </td>
                            <td>
                                <?php if ($report['verification_status'] === 'verified'): ?>
                                    <span class="badge bg-success status-badge">
                                        <i class="fas fa-check"></i> Verified
                                    </span>
                                <?php else: ?>
                                    <span class="badge bg-warning status-badge">
                                        <i class="fas fa-clock"></i> Pending
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($report['verification_status'] === 'verified'): ?>
                                    <?php echo date('M d, Y', strtotime($report['verified_at'])); ?>
                                    <br>
                                    <small class="text-muted">by <?php echo htmlspecialchars($report['verified_by_name']); ?></small>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="../reports/view_report.php?report_id=<?php echo $report['report_id']; ?>" class="btn btn-primary btn-sm" onclick="event.stopPropagation();">

                                    <i class="fas fa-eye"></i> View Details
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

        <?php if (!empty($reports)): ?>
            <div class="row mt-4">
                <div class="col-12">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        <strong>Note:</strong> All reports are automatically submitted for verification. Once verified by an administrator, you cannot modify the report data.
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script>

        document.querySelectorAll('.summary-card').forEach(card => {
            card.addEventListener('click', function() {
                this.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    this.style.transform = 'scale(1)';
                }, 150);
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>