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

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

$success_message = "";
$error_message = "";
$shift_id = isset($_GET['shift_id']) ? $_GET['shift_id'] : (isset($_POST['shift_id']) ? $_POST['shift_id'] : 0);

// Get shift details
$shift_sql = "SELECT * FROM shift_entries WHERE id='$shift_id' AND status='OPEN'";
$shift_result = mysqli_query($conn, $shift_sql);
$shift = mysqli_fetch_assoc($shift_result);

if(!$shift) {
    header("Location: shift_open.php");
    exit();
}

// Get nozzle readings for this shift
$readings_sql = "SELECT nr.*, n.nozzle_name, t.tank_name, f.name as fuel_name, f.sale_price 
                 FROM nozzle_readings nr
                 LEFT JOIN nozzles n ON nr.nozzle_id = n.id
                 LEFT JOIN tanks t ON n.tank_id = t.id
                 LEFT JOIN fuel_types f ON t.fuel_type_id = f.id
                 WHERE nr.shift_id='$shift_id'";
$readings_result = mysqli_query($conn, $readings_sql);
$has_readings = mysqli_num_rows($readings_result) > 0;

if(!$has_readings) {
    header("Location: nozzle_readings.php?shift_id=$shift_id");
    exit();
}

// Calculate totals
$total_sales_liters = 0;
$total_sales_amount = 0; // New: total sales in rupees
$readings_data = [];

// Get fuel price for each nozzle (from fuel_types via tanks)
while($row = mysqli_fetch_assoc($readings_result)) {
    $total_sales_liters += $row['sale_liters'];
    // Calculate sale amount based on fuel type's sale price
    $sale_price = isset($row['sale_price']) ? $row['sale_price'] : 0;
    $sale_amount = $row['sale_liters'] * $sale_price;
    $total_sales_amount += $sale_amount;
    
    // Store with calculated amount
    $row['sale_amount'] = $sale_amount;
    $readings_data[] = $row;
}

// Get total purchases (optional - from purchases table)
$purchases_sql = "SELECT SUM(total_amount) as total_purchases FROM purchases";
$purchases_result = mysqli_query($conn, $purchases_sql);
$purchases = mysqli_fetch_assoc($purchases_result);
$total_purchases = $purchases['total_purchases'] ? $purchases['total_purchases'] : 0;

// Get total expenses
$expenses_sql = "SELECT SUM(expense_amount) as total_expenses FROM expenses";
$expenses_result = mysqli_query($conn, $expenses_sql);
$expenses = mysqli_fetch_assoc($expenses_result);
$total_expenses = $expenses['total_expenses'] ? $expenses['total_expenses'] : 0;

// Calculate net cash = Total Sales Amount (in rupees) - Total Expenses
$net_cash = $total_sales_amount - $total_expenses;

// Close shift
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['close_shift'])) {
    // First, record the shift closing summary (optional - you can create a shift_summary table)
    $close_sql = "UPDATE shift_entries SET status='CLOSED' WHERE id='$shift_id'";
    if(mysqli_query($conn, $close_sql)) {
        $success_message = "Shift closed successfully!";
        header("Refresh: 2; url=shift_open.php");
    } else {
        $error_message = "Error closing shift: " . mysqli_error($conn);
    }
}
?>

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

<div class="container-fluid">
    <div class="shift-close-container">
        <!-- Header -->
        <div class="shift-header">
            <div class="header-icon">
                <i class="fas fa-door-closed"></i>
            </div>
            <div class="header-text">
                <h2>Close Shift - <?php echo $shift['shift_name']; ?> Shift</h2>
                <p>Review shift summary and confirm closure</p>
            </div>
        </div>

        <?php if($success_message): ?>
            <div class="alert-custom alert-success">
                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
            </div>
        <?php endif; ?>
        
        <?php if($error_message): ?>
            <div class="alert-custom alert-danger">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
            </div>
        <?php endif; ?>

        <div class="row g-4">
            <!-- Shift Summary Card -->
            <div class="col-md-5">
                <div class="summary-card">
                    <div class="card-header-custom">
                        <i class="fas fa-chart-line"></i>
                        <h4>Shift Summary</h4>
                    </div>
                    <div class="card-body-custom">
                        <div class="summary-item">
                            <div class="summary-label">
                                <i class="fas fa-tag"></i> Shift Name:
                            </div>
                            <div class="summary-value">
                                <strong><?php echo $shift['shift_name']; ?></strong>
                            </div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">
                                <i class="fas fa-play-circle"></i> Shift Opened:
                            </div>
                            <div class="summary-value">
                                <?php echo date('d-m-Y h:i:s A', strtotime($shift['date_time'])); ?>
                            </div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">
                                <i class="fas fa-stop-circle"></i> Closing Time:
                            </div>
                            <div class="summary-value">
                                <?php echo date('d-m-Y h:i:s A'); ?>
                            </div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">
                                <i class="fas fa-gas-pump"></i> Total Fuel Sold:
                            </div>
                            <div class="summary-value text-success">
                                <strong><?php echo number_format($total_sales_liters, 2); ?> Liters</strong>
                            </div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">
                                <i class="fas fa-shopping-cart"></i> Total Purchases:
                            </div>
                            <div class="summary-value">
                                Rs <?php echo number_format($total_purchases, 2); ?>
                            </div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">
                                <i class="fas fa-receipt"></i> Total Expenses:
                            </div>
                            <div class="summary-value text-danger">
                                Rs <?php echo number_format($total_expenses, 2); ?>
                            </div>
                        </div>
                        <div class="summary-item total-row">
                            <div class="summary-label">
                                <i class="fas fa-money-bill-wave"></i> Net Cash:
                            </div>
                            <div class="summary-value net-cash">
                                Rs <?php echo number_format($net_cash, 2); ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Nozzle-wise Sales Card -->
            <div class="col-md-7">
                <div class="sales-card">
                    <div class="card-header-custom">
                        <i class="fas fa-list"></i>
                        <h4>Nozzle-wise Sales</h4>
                    </div>
                    <div class="card-body-custom">
                        <div class="table-responsive">
                            <table class="modern-table">
                                <thead>
                                    <tr>
                                        <th>Nozzle</th>
                                        <th>Opening (L)</th>
                                        <th>Closing (L)</th>
                                        <th>Sale (L)</th>
                                        <th>Amount (Rs)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($readings_data as $reading): ?>
                                        <tr>
                                            <td>
                                                <div class="nozzle-cell">
                                                    <i class="fas fa-oil-can"></i>
                                                    <strong><?php echo htmlspecialchars($reading['nozzle_name']); ?></strong>
                                                </div>
                                            </td>
                                            <td><?php echo number_format($reading['opening_reading'], 2); ?></td>
                                            <td><?php echo number_format($reading['closing_reading'], 2); ?></td>
                                            <td class="sale-liters"><?php echo number_format($reading['sale_liters'], 2); ?></td>
                                            <td class="sale-amount">Rs <?php echo number_format($reading['sale_amount'], 2); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr class="total-row">
                                        <td colspan="3"><strong>Total</strong></td>
                                        <td><strong><?php echo number_format($total_sales_liters, 2); ?> L</strong></td>
                                        <td><strong>Rs <?php echo number_format($total_sales_amount, 2); ?></strong></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="action-buttons-container">
            <form method="POST" action="" onsubmit="return confirm('Are you sure you want to close this shift? This action cannot be undone!');">
                <input type="hidden" name="shift_id" value="<?php echo $shift_id; ?>">
                <button type="submit" name="close_shift" class="btn-close-shift">
                    <i class="fas fa-check-circle"></i> Confirm & Close Shift
                </button>
                <a href="shift_open.php" class="btn-cancel">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </form>
        </div>
    </div>
</div>

<style>
/* Shift Close Page Styles */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

* {
    font-family: 'Poppins', sans-serif;
}

h1, h2, h3, h4, .card-header-custom h4, .summary-label {
    font-family: 'Times New Roman', serif;
}

.shift-close-container {
    padding: 0;
}

/* Header */
.shift-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 20px;
    padding: 25px 30px;
    margin-bottom: 30px;
    display: flex;
    align-items: center;
    gap: 20px;
    color: #fff;
}

.header-icon i {
    font-size: 48px;
    color: rgba(255,255,255,0.9);
}

.header-text h2 {
    margin: 0 0 5px 0;
    font-size: 28px;
    color: #fff;
}

.header-text p {
    margin: 0;
    color: rgba(255,255,255,0.9);
    font-size: 14px;
}

/* Alert Styles */
.alert-custom {
    padding: 15px 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    animation: slideIn 0.3s ease;
    font-weight: 500;
}

@keyframes slideIn {
    from { transform: translateY(-20px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border-left: 4px solid #dc3545;
}

.close-alert {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    opacity: 0.5;
    transition: opacity 0.3s;
}

.close-alert:hover {
    opacity: 1;
}

/* Summary Card */
.summary-card, .sales-card {
    background: #fff;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 5px 20px rgba(0,0,0,0.08);
    height: 100%;
}

.card-header-custom {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    padding: 18px 25px;
    display: flex;
    align-items: center;
    gap: 12px;
    color: #fff;
}

.card-header-custom i {
    font-size: 22px;
}

.card-header-custom h4 {
    margin: 0;
    font-size: 18px;
    color: #fff;
}

.card-body-custom {
    padding: 25px;
}

/* Summary Items */
.summary-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 0;
    border-bottom: 1px solid #f0f0f0;
}

.summary-item:last-child {
    border-bottom: none;
}

.summary-label {
    font-weight: 600;
    color: #555;
    font-size: 14px;
}

.summary-label i {
    color: #A04657;
    margin-right: 8px;
    width: 20px;
}

.summary-value {
    font-weight: 500;
    color: #333;
    font-size: 14px;
}

.text-success {
    color: #28a745 !important;
}

.text-danger {
    color: #dc3545 !important;
}

.total-row {
    background: #f8f9fa;
    margin-top: 10px;
    border-radius: 10px;
    padding: 12px;
    margin-top: 15px;
}

.total-row .summary-label {
    font-size: 16px;
    font-weight: 700;
    color: #A04657;
}

.net-cash {
    font-size: 24px;
    font-weight: 700;
    color: #A04657;
}

/* Modern Table */
.modern-table {
    width: 100%;
    border-collapse: collapse;
}

.modern-table th {
    padding: 12px 15px;
    background: #f8f9fa;
    font-weight: 600;
    color: #555;
    font-size: 13px;
    border-bottom: 2px solid #e0e0e0;
}

.modern-table td {
    padding: 12px 15px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
    font-size: 13px;
}

.modern-table tfoot tr {
    background: #f8f9fa;
    font-weight: 600;
}

.modern-table tfoot td {
    border-top: 2px solid #e0e0e0;
    border-bottom: none;
}

.nozzle-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.nozzle-cell i {
    color: #A04657;
    font-size: 16px;
}

.sale-liters {
    color: #28a745;
    font-weight: 600;
}

.sale-amount {
    color: #A04657;
    font-weight: 600;
}

/* Action Buttons */
.action-buttons-container {
    margin-top: 30px;
    text-align: center;
    padding: 20px 0;
}

.btn-close-shift {
    background: linear-gradient(135deg, #dc3545 0%, #b02a37 100%);
    color: #fff;
    border: none;
    padding: 14px 35px;
    border-radius: 50px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    margin-right: 15px;
    box-shadow: 0 4px 12px rgba(220,53,69,0.3);
}

.btn-close-shift:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(220,53,69,0.4);
}

.btn-cancel {
    background: #6c757d;
    color: #fff;
    border: none;
    padding: 14px 35px;
    border-radius: 50px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
    transition: all 0.3s;
    box-shadow: 0 4px 12px rgba(108,117,125,0.3);
}

.btn-cancel:hover {
    background: #5a6268;
    transform: translateY(-2px);
    color: #fff;
    text-decoration: none;
}

/* Responsive */
@media (max-width: 768px) {
    .shift-header {
        flex-direction: column;
        text-align: center;
    }
    
    .summary-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 5px;
    }
    
    .btn-close-shift, .btn-cancel {
        display: block;
        width: 100%;
        margin: 10px 0;
    }
    
    .btn-cancel {
        margin-right: 0;
    }
    
    .modern-table th, .modern-table td {
        white-space: nowrap;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
</style>

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