<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$success_message = "";
$error_message = "";

// Filter variables
$filter_fuel_type = isset($_GET['fuel_type']) ? $_GET['fuel_type'] : '';
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$filter_date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$filter_date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Get all fuel types for filter dropdown
$fuel_sql = "SELECT * FROM fuel_types ORDER BY name";
$fuel_result = mysqli_query($conn, $fuel_sql);

// Build WHERE clause for filters
$where_clauses = [];
if($filter_fuel_type) {
    $where_clauses[] = "rr.fuel_type_id = '$filter_fuel_type'";
}
if($filter_status) {
    $where_clauses[] = "rr.status = '$filter_status'";
}
if($filter_date_from) {
    $where_clauses[] = "DATE(rr.date_time) >= '$filter_date_from'";
}
if($filter_date_to) {
    $where_clauses[] = "DATE(rr.date_time) <= '$filter_date_to'";
}

$where_sql = !empty($where_clauses) ? "WHERE " . implode(" AND ", $where_clauses) : "";

// Get all rate revisions with filters
$revisions_sql = "SELECT rr.*, ft.name as fuel_name 
                  FROM rate_revisions rr 
                  LEFT JOIN fuel_types ft ON rr.fuel_type_id = ft.id 
                  $where_sql
                  ORDER BY rr.id DESC";
$revisions_result = mysqli_query($conn, $revisions_sql);

// Calculate Summary Statistics
$total_revisions = 0;
$total_gain = 0;
$total_loss = 0;
$total_stock_affected = 0;

$summary_data = [];
while($rev = mysqli_fetch_assoc($revisions_result)) {
    $total_revisions++;
    $total_stock_affected += $rev['stock_quantity'];
    if($rev['gain_loss'] > 0) {
        $total_gain += $rev['gain_loss'];
    } elseif($rev['gain_loss'] < 0) {
        $total_loss += abs($rev['gain_loss']);
    }
}
mysqli_data_seek($revisions_result, 0);

$net_impact = $total_gain - $total_loss;
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rate Revision Report</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');
        
        * {
            font-family: 'Poppins', sans-serif;
        }
        
        h1, h2, h3, h4, h5, h6, .card-header h4, .table th {
            font-family: 'Times New Roman', serif;
        }
        
        body {
            background: #f5f5f5;
        }
        
        .main-container {
            padding: 20px;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            border-radius: 15px;
            padding: 25px 30px;
            margin-bottom: 30px;
            color: #fff;
        }
        
        .page-header h2 {
            margin: 0 0 8px 0;
            font-size: 28px;
            color: #fff;
        }
        
        .page-header p {
            margin: 0;
            opacity: 0.95;
            font-weight: 500;
        }
        
        /* Stat Cards */
        .stat-card {
            background: #fff;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border-left: 4px solid #A04657;
            transition: all 0.3s;
        }
        
        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 20px rgba(160,70,87,0.15);
        }
        
        .stat-icon {
            width: 50px;
            height: 50px;
            background: rgba(160,70,87,0.1);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 15px;
        }
        
        .stat-icon i {
            font-size: 24px;
            color: #A04657;
        }
        
        .stat-value {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #666;
            font-size: 13px;
            font-weight: 500;
        }
        
        .stat-gain {
            color: #28a745;
        }
        
        .stat-loss {
            color: #dc3545;
        }
        
        /* Filter Card */
        .filter-card {
            background: #fff;
            border-radius: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        
        .filter-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .filter-header h5 {
            margin: 0;
            font-weight: 600;
            color: #333;
        }
        
        .filter-body {
            padding: 20px;
        }
        
        .filter-label {
            font-weight: 600;
            margin-bottom: 8px;
            color: #555;
            font-size: 13px;
        }
        
        .filter-label i {
            color: #A04657;
            margin-right: 5px;
        }
        
        .form-control, .form-select {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 8px 12px;
            font-weight: 500;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #A04657;
            box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
        }
        
        .btn-filter {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            color: #fff;
            border: none;
            padding: 10px 25px;
            border-radius: 10px;
            font-weight: 600;
            margin-top: 30px;
            width: 100%;
        }
        
        .btn-filter:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(160,70,87,0.3);
            color: #fff;
        }
        
        .btn-reset {
            background: #6c757d;
            color: #fff;
            border: none;
            padding: 10px 25px;
            border-radius: 10px;
            font-weight: 600;
            margin-top: 30px;
            width: 100%;
        }
        
        .btn-reset:hover {
            background: #5a6268;
            color: #fff;
        }
        
        .btn-export {
            background: #28a745;
            color: #fff;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 600;
        }
        
        .btn-export:hover {
            background: #218838;
            color: #fff;
        }
        
        /* Table Card */
        .table-card {
            background: #fff;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        
        .table-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .table-header h4 {
            margin: 0;
            font-weight: 600;
            color: #333;
        }
        
        .table-responsive {
            padding: 0;
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table th {
            background: #f8f9fa;
            font-weight: 700;
            color: #444;
            border-bottom: 2px solid #dee2e6;
            padding: 12px 15px;
        }
        
        .table td {
            padding: 12px 15px;
            vertical-align: middle;
            font-weight: 500;
        }
        
        .badge-gain {
            background: #28a745;
            color: #fff;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-loss {
            background: #dc3545;
            color: #fff;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-neutral {
            background: #ffc107;
            color: #856404;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .amount-gain {
            color: #28a745;
            font-weight: 700;
        }
        
        .amount-loss {
            color: #dc3545;
            font-weight: 700;
        }
        
        .empty-state {
            text-align: center;
            padding: 50px;
        }
        
        .empty-state i {
            font-size: 64px;
            color: #ccc;
            margin-bottom: 20px;
        }
        
        .empty-state p {
            color: #666;
            font-weight: 500;
        }
        
        @media (max-width: 768px) {
            .main-container {
                padding: 15px;
            }
            
            .page-header {
                padding: 20px;
            }
            
            .page-header h2 {
                font-size: 22px;
            }
            
            .stat-value {
                font-size: 22px;
            }
            
            .table th, .table td {
                font-size: 12px;
                padding: 8px 10px;
            }
            
            .table-header {
                flex-direction: column;
            }
        }
        
        @media print {
            .filter-card, .btn-export, .page-header .btn {
                display: none;
            }
            
            .stat-card {
                break-inside: avoid;
            }
            
            .table-card {
                break-inside: avoid;
            }
        }
    </style>
</head>
<body>
<div class="main-container">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="pageHeader">
            <div class="d-flex justify-content-between align-items-center flex-wrap">
                <div>
                    <h2><i class="fas fa-chart-line"></i> Rate Revision Report</h2>
                    <p>Track all fuel rate changes and their financial impact</p>
                </div>
                <div>
                    <button onclick="window.print()" class="btn-export">
                        <i class="fas fa-print"></i> Print Report
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Statistics Cards -->
        <div class="row g-4 mb-4">
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-history"></i>
                    </div>
                    <div class="stat-value"><?php echo $total_revisions; ?></div>
                    <div class="stat-label">Total Revisions</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="stat-value stat-gain">+Rs <?php echo number_format($total_gain, 2); ?></div>
                    <div class="stat-label">Total Gain</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="stat-value stat-loss">-Rs <?php echo number_format($total_loss, 2); ?></div>
                    <div class="stat-label">Total Loss</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-calculator"></i>
                    </div>
                    <div class="stat-value <?php echo $net_impact >= 0 ? 'stat-gain' : 'stat-loss'; ?>">
                        <?php echo $net_impact >= 0 ? '+' : ''; ?>Rs <?php echo number_format($net_impact, 2); ?>
                    </div>
                    <div class="stat-label">Net Impact</div>
                </div>
            </div>
        </div>
        
        <!-- Filter Card -->
        <div class="filter-card">
            <div class="filter-header">
                <h5><i class="fas fa-filter"></i> Filter Reports</h5>
            </div>
            <div class="filter-body">
                <form method="GET" action="">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="filter-label"><i class="fas fa-gas-pump"></i> Fuel Type</label>
                            <select name="fuel_type" class="form-select">
                                <option value="">-- All Fuel Types --</option>
                                <?php 
                                mysqli_data_seek($fuel_result, 0);
                                while($fuel = mysqli_fetch_assoc($fuel_result)): 
                                    $selected = ($filter_fuel_type == $fuel['id']) ? 'selected' : '';
                                ?>
                                    <option value="<?php echo $fuel['id']; ?>" <?php echo $selected; ?>>
                                        <?php echo htmlspecialchars($fuel['name']); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="filter-label"><i class="fas fa-tag"></i> Status</label>
                            <select name="status" class="form-select">
                                <option value="">-- All Status --</option>
                                <option value="GAIN" <?php echo $filter_status == 'GAIN' ? 'selected' : ''; ?>>GAIN</option>
                                <option value="LOSS" <?php echo $filter_status == 'LOSS' ? 'selected' : ''; ?>>LOSS</option>
                                <option value="NEUTRAL" <?php echo $filter_status == 'NEUTRAL' ? 'selected' : ''; ?>>NEUTRAL</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="filter-label"><i class="fas fa-calendar-alt"></i> Date From</label>
                            <input type="date" name="date_from" class="form-control" value="<?php echo $filter_date_from; ?>">
                        </div>
                        <div class="col-md-3">
                            <label class="filter-label"><i class="fas fa-calendar-alt"></i> Date To</label>
                            <input type="date" name="date_to" class="form-control" value="<?php echo $filter_date_to; ?>">
                        </div>
                        <div class="col-md-1">
                            <button type="submit" class="btn-filter">
                                <i class="fas fa-search"></i> Filter
                            </button>
                        </div>
                        <div class="col-md-1">
                            <a href="rate_revision_report.php" class="btn-reset d-block text-center">
                                <i class="fas fa-undo-alt"></i> Reset
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Rate Revisions Table -->
        <div class="table-card">
            <div class="table-header">
                <h4><i class="fas fa-list"></i> Rate Revision History</h4>
                <div>
                    <span class="text-muted">
                        <i class="fas fa-database"></i> Total Stock Affected: <?php echo number_format($total_stock_affected, 2); ?> Liters
                    </span>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>#ID</th>
                            <th>Fuel Type</th>
                            <th>Old Rate</th>
                            <th>New Rate</th>
                            <th>Difference</th>
                            <th>Stock (Liters)</th>
                            <th>Gain/Loss Amount</th>
                            <th>Status</th>
                            <th>Date & Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(mysqli_num_rows($revisions_result) > 0): ?>
                            <?php while($revision = mysqli_fetch_assoc($revisions_result)): 
                                $rate_diff = $revision['new_rate'] - $revision['old_rate'];
                            ?>
                                <tr>
                                    <td><strong>#<?php echo $revision['id']; ?></strong></td>
                                    <td>
                                        <i class="fas fa-oil-can" style="color: #A04657;"></i>
                                        <strong><?php echo htmlspecialchars($revision['fuel_name']); ?></strong>
                                    </td>
                                    <td>Rs <?php echo number_format($revision['old_rate'], 2); ?></td>
                                    <td>Rs <?php echo number_format($revision['new_rate'], 2); ?></td>
                                    <td class="<?php echo $rate_diff > 0 ? 'amount-gain' : ($rate_diff < 0 ? 'amount-loss' : ''); ?>">
                                        <?php echo $rate_diff > 0 ? '+' : ''; ?>Rs <?php echo number_format($rate_diff, 2); ?>
                                    </td>
                                    <td><?php echo number_format($revision['stock_quantity'], 2); ?></td>
                                    <td class="<?php echo $revision['gain_loss'] > 0 ? 'amount-gain' : ($revision['gain_loss'] < 0 ? 'amount-loss' : ''); ?>">
                                        <strong>
                                            <?php echo $revision['gain_loss'] > 0 ? '+' : ''; ?>Rs <?php echo number_format($revision['gain_loss'], 2); ?>
                                        </strong>
                                    </td>
                                    <td>
                                        <?php if($revision['gain_loss'] > 0): ?>
                                            <span class="badge-gain">
                                                <i class="fas fa-arrow-up"></i> GAIN
                                            </span>
                                        <?php elseif($revision['gain_loss'] < 0): ?>
                                            <span class="badge-loss">
                                                <i class="fas fa-arrow-down"></i> LOSS
                                            </span>
                                        <?php else: ?>
                                            <span class="badge-neutral">
                                                <i class="fas fa-minus"></i> NEUTRAL
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <i class="fas fa-calendar-alt"></i>
                                        <?php echo date('d-m-Y', strtotime($revision['date_time'])); ?>
                                        <br>
                                        <small class="text-muted">
                                            <i class="fas fa-clock"></i> <?php echo date('h:i A', strtotime($revision['date_time'])); ?>
                                        </small>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="9" class="empty-state">
                                    <i class="fas fa-chart-line"></i>
                                    <p>No rate revision records found</p>
                                    <small class="text-muted">Try changing filters or create a new rate revision</small>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
    // Auto-submit when filter changes (optional)
    document.querySelectorAll('.filter-auto').forEach(function(element) {
        element.addEventListener('change', function() {
            this.closest('form').submit();
        });
    });
</script>

<?php include('../includes/ft.php'); ?>
</body>
</html>