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

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

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

// Open Shift
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['open_shift'])) {
    $shift_name = mysqli_real_escape_string($conn, $_POST['shift_name']);
    $date_time = date('Y-m-d H:i:s');
    
    // Check if shift already open
    $check_sql = "SELECT id FROM shift_entries WHERE shift_name='$shift_name' AND status='OPEN'";
    $check_result = mysqli_query($conn, $check_sql);
    
    if(mysqli_num_rows($check_result) > 0) {
        $error_message = "This shift is already OPEN! Please close it first.";
    } else {
        $sql = "INSERT INTO shift_entries (shift_name, date_time, status) VALUES ('$shift_name', '$date_time', 'OPEN')";
        if(mysqli_query($conn, $sql)) {
            $success_message = "Shift opened successfully!";
        } else {
            $error_message = "Error: " . mysqli_error($conn);
        }
    }
}

// Get all open shifts
$open_shifts_sql = "SELECT * FROM shift_entries WHERE status='OPEN' ORDER BY id DESC";
$open_shifts_result = mysqli_query($conn, $open_shifts_sql);

// Get statistics
$total_open_shifts = mysqli_num_rows($open_shifts_result);
$shifts_by_type = ['Morning' => 0, 'Evening' => 0, 'Night' => 0];

while($shift = mysqli_fetch_assoc($open_shifts_result)) {
    $shifts_by_type[$shift['shift_name']]++;
}
mysqli_data_seek($open_shifts_result, 0);
?>

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

<div class="shift-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-door-open"></i> Shift Management</h2>
            <p>Open new shifts and manage active shifts for fuel dispensing</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span><?php echo $total_open_shifts; ?> Active Shifts</span>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-door-open"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo $total_open_shifts; ?></h3>
                <p>Open Shifts</p>
                <span class="stat-trend">Currently Active</span>
            </div>
        </div>
        <div class="stat-card morning-stat">
            <div class="stat-icon">
                <i class="fas fa-sun"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo $shifts_by_type['Morning']; ?></h3>
                <p>Morning Shift</p>
                <span class="stat-trend">06:00 - 14:00</span>
            </div>
        </div>
        <div class="stat-card evening-stat">
            <div class="stat-icon">
                <i class="fas fa-cloud-sun"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo $shifts_by_type['Evening']; ?></h3>
                <p>Evening Shift</p>
                <span class="stat-trend">14:00 - 22:00</span>
            </div>
        </div>
        <div class="stat-card night-stat">
            <div class="stat-icon">
                <i class="fas fa-moon"></i>
            </div>
            <div class="stat-info">
                <h3><?php echo $shifts_by_type['Night']; ?></h3>
                <p>Night Shift</p>
                <span class="stat-trend">22:00 - 06:00</span>
            </div>
        </div>
    </div>

    <!-- Alerts -->
    <?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="content-grid">
        <!-- Open Shift Form -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-plus-circle"></i>
                <h4>Open New Shift</h4>
            </div>
                                                <div class="form-card-body">

                                                    <form method="POST" action="">
                                                        
                                                        <div class="input-group-custom">
                                                            <label>
                                                                <i class="fas fa-clock"></i> 
                                                                Shift Timing 
                                                                <span class="required">*</span>
                                                            </label>
                                                
                                                            <!-- Single Shift -->
                                                            <input 
                                                                type="text" 
                                                                class="form-control-modern" 
                                                                value="24 Hours Shift (06:00 AM - Next Day 06:00 AM)" 
                                                                readonly
                                                            >
                                                
                                                            <!-- Hidden Value -->
                                                            <input type="hidden" name="shift_name" value="24 Hours Shift">
                                                
                                                            <small class="input-help">
                                                                Only one shift runs from 06:00 AM to next day 06:00 AM
                                                            </small>
                                                        </div>
                                                
                                                        <button type="submit" name="open_shift" class="btn-submit">
                                                            <i class="fas fa-door-open"></i> Open Shift
                                                        </button>
                                                
                                                    </form>
                                                
                                                </div>
        </div>
        
        <!-- Open Shifts List -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-list"></i>
                    <h4>Currently Open Shifts</h4>
                </div>
                <div class="table-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="tableSearch" placeholder="Search shift..." class="search-input">
                </div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="shiftsTable">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Shift Name</th>
                                <th>Opened At</th>
                                <th>Status</th>
                                <th>Duration</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($open_shifts_result) > 0): ?>
                                <?php while($row = mysqli_fetch_assoc($open_shifts_result)): 
                                    $opened_time = strtotime($row['date_time']);
                                    $current_time = time();
                                    $duration_seconds = $current_time - $opened_time;
                                    $duration_hours = floor($duration_seconds / 3600);
                                    $duration_minutes = floor(($duration_seconds % 3600) / 60);
                                    $duration_text = $duration_hours . "h " . $duration_minutes . "m";
                                    
                                    // Set icon based on shift name
                                    if($row['shift_name'] == 'Morning') {
                                        $shift_icon = 'fa-sun';
                                        $shift_color = '#f39c12';
                                    } elseif($row['shift_name'] == 'Evening') {
                                        $shift_icon = 'fa-cloud-sun';
                                        $shift_color = '#e67e22';
                                    } else {
                                        $shift_icon = 'fa-moon';
                                        $shift_color = '#8e44ad';
                                    }
                                ?>
                                    <tr>
                                        <td data-label="ID"><?php echo $row['id']; ?></td>
                                        <td data-label="Shift Name">
                                            <div class="shift-name-cell">
                                                <i class="fas <?php echo $shift_icon; ?>" style="color: <?php echo $shift_color; ?>"></i>
                                                <strong><?php echo $row['shift_name']; ?> Shift</strong>
                                            </div>
                                        </div>
                                        <td data-label="Opened At">
                                            <div class="date-cell">
                                                <span class="date-main">
                                                    <i class="fas fa-calendar-alt"></i>
                                                    <?php echo date('d-m-Y', strtotime($row['date_time'])); ?>
                                                </span>
                                                <span class="time-main">
                                                    <i class="fas fa-clock"></i>
                                                    <?php echo date('h:i A', strtotime($row['date_time'])); ?>
                                                </span>
                                            </div>
                                        </div>
                                        <td data-label="Status">
                                            <span class="status-badge status-open">
                                                <i class="fas fa-circle"></i>
                                                OPEN
                                            </span>
                                        </div>
                                        <td data-label="Duration">
                                            <div class="duration-cell">
                                                <i class="fas fa-hourglass-half"></i>
                                                <strong><?php echo $duration_text; ?></strong>
                                            </div>
                                        </div>
                                        <td data-label="Actions">
                                            <div class="action-buttons">
                                                <a href="shift_close.php?shift_id=<?php echo $row['id']; ?>" 
                                                   class="btn-action btn-close" title="Close Shift">
                                                    <i class="fas fa-door-closed"></i>
                                                    Close
                                                </a>
                                            </div>
                                        </div>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="empty-state">
                                        <i class="fas fa-door-open"></i>
                                        <p>No open shifts found</p>
                                        <small>Click "Open New Shift" to start a shift</small>
                                    </div>
                                    </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

body {
    background: #f5f7fb;
    overflow-x: hidden;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.stat-info h3,
.form-card-header h4,
.header-info h4,
.modern-table th {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

/* Main Content */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    background: #f5f7fb;
}

.shift-container {
    max-width: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 16px;
    padding: 16px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    font-size: 22px;
    margin-bottom: 4px;
}

.page-header p {
    font-size: 12px;
    opacity: 0.92;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 6px 20px;
    border-radius: 40px;
    font-weight: 600;
    font-size: 12px;
}

/* Statistics Cards */
.stats-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 20px;
    width: 100%;
}

.stat-card {
    background: #fff;
    border-radius: 16px;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    border: 1px solid #eef2f6;
    transition: all 0.3s;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 18px rgba(160,70,87,0.1);
}

.stat-icon {
    width: 52px;
    height: 52px;
    background: rgba(160,70,87,0.1);
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.stat-icon i {
    font-size: 26px;
    color: #A04657;
}

.morning-stat .stat-icon i { color: #f39c12; }
.morning-stat .stat-icon { background: rgba(243,156,18,0.1); }
.evening-stat .stat-icon i { color: #e67e22; }
.evening-stat .stat-icon { background: rgba(230,126,34,0.1); }
.night-stat .stat-icon i { color: #8e44ad; }
.night-stat .stat-icon { background: rgba(142,68,173,0.1); }

.stat-info h3 {
    font-size: 24px;
    margin: 0;
    font-weight: 700;
    color: #1a2a3a;
}

.stat-info p {
    margin: 4px 0 0;
    font-weight: 500;
    color: #64748b;
    font-size: 11px;
}

.stat-trend {
    font-size: 10px;
    color: #94a3b8;
    display: block;
    margin-top: 3px;
}

/* Alerts */
.alert-custom {
    padding: 12px 20px;
    border-radius: 14px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 13px;
    width: 100%;
}

.alert-success {
    background: #e8f5e9;
    color: #2e7d32;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #ffebee;
    color: #c62828;
    border-left: 4px solid #dc3545;
}

.close-alert {
    background: none;
    border: none;
    font-size: 22px;
    cursor: pointer;
    opacity: 0.5;
}

/* Content Grid */
.content-grid {
    display: grid;
    grid-template-columns: 380px 1fr;
    gap: 20px;
    width: 100%;
}

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 16px;
    border: 1px solid #eef2f6;
    overflow: hidden;
}

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

.form-card-header i {
    font-size: 18px;
}

.form-card-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.form-card-body {
    padding: 20px;
}

.input-group-custom {
    margin-bottom: 16px;
}

.input-group-custom label {
    display: block;
    margin-bottom: 6px;
    font-weight: 600;
    color: #1e293b;
    font-size: 12px;
}

.input-group-custom label i {
    color: #A04657;
    margin-right: 5px;
}

.required {
    color: #dc3545;
}

.form-control-modern {
    width: 100%;
    padding: 9px 12px;
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    font-size: 13px;
    font-weight: 500;
    background: #fefefe;
    transition: all 0.3s;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    background: #fff;
}

.input-help {
    display: block;
    font-size: 10px;
    color: #94a3b8;
    margin-top: 4px;
}

.btn-submit {
    width: 100%;
    padding: 10px;
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(160,70,87,0.3);
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    border: 1px solid #eef2f6;
    overflow: hidden;
    width: 100%;
}

.table-card-header {
    padding: 12px 20px;
    border-bottom: 1px solid #eef2f6;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.header-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-info i {
    font-size: 18px;
    color: #A04657;
}

.header-info h4 {
    margin: 0;
    font-size: 15px;
}

.table-search {
    position: relative;
}

.table-search i {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #94a3b8;
    font-size: 11px;
}

.search-input {
    padding: 7px 12px 7px 32px;
    border: 2px solid #e2e8f0;
    border-radius: 30px;
    width: 200px;
    font-size: 12px;
}

.search-input:focus {
    border-color: #A04657;
    outline: none;
}

.table-responsive {
    overflow-x: auto;
    width: 100%;
}

/* Modern Table */
.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 700px;
}

.modern-table th {
    padding: 10px 12px;
    background: #f8fafc;
    font-weight: 700;
    color: #475569;
    font-size: 11px;
    border-bottom: 2px solid #eef2f6;
    text-align: left;
}

.modern-table td {
    padding: 9px 12px;
    border-bottom: 1px solid #f0f4f9;
    font-size: 12px;
    font-weight: 500;
    color: #1e293b;
    vertical-align: middle;
}

.modern-table tr:hover td {
    background: #fefaf8;
}

.shift-name-cell {
    display: flex;
    align-items: center;
    gap: 6px;
}

.shift-name-cell i {
    font-size: 14px;
}

.date-cell {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.date-main, .time-main {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 11px;
}

.date-main i, .time-main i {
    color: #94a3b8;
    font-size: 10px;
}

.duration-cell {
    display: flex;
    align-items: center;
    gap: 6px;
}

.duration-cell i {
    color: #A04657;
    font-size: 13px;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 3px 10px;
    border-radius: 30px;
    font-size: 10px;
    font-weight: 600;
}

.status-open {
    background: #e8f5e9;
    color: #28a745;
}

.status-open i {
    font-size: 8px;
}

.action-buttons {
    display: flex;
    gap: 6px;
}

.btn-action {
    padding: 5px 12px;
    border-radius: 30px;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    text-decoration: none;
    font-size: 11px;
    font-weight: 600;
    transition: all 0.3s;
}

.btn-close {
    background: #fff3e0;
    color: #f39c12;
}

.btn-close:hover {
    background: #f39c12;
    color: #fff;
    transform: scale(1.03);
}

.empty-state {
    text-align: center;
    padding: 40px !important;
}

.empty-state i {
    font-size: 48px;
    color: #A04657;
    opacity: 0.35;
    margin-bottom: 10px;
    display: block;
}

.empty-state p {
    font-size: 13px;
    font-weight: 600;
    color: #475569;
    margin-bottom: 4px;
}

.empty-state small {
    font-size: 11px;
    color: #94a3b8;
}

/* Responsive */
@media (max-width: 1100px) {
    .content-grid {
        grid-template-columns: 1fr;
    }
    .stats-row {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 992px) {
    .main-content {
        margin-left: 0;
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 10px 12px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .stats-row {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .table-card-header {
        flex-direction: column;
        align-items: stretch;
    }
    .search-input {
        width: 100%;
    }
    .action-buttons {
        justify-content: center;
    }
    .form-card-body {
        padding: 16px;
    }
    .stat-card {
        padding: 12px 16px;
    }
    .stat-icon {
        width: 44px;
        height: 44px;
    }
    .stat-icon i {
        font-size: 22px;
    }
    .stat-info h3 {
        font-size: 20px;
    }
    .modern-table th {
        display: none;
    }
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 45%;
        position: relative;
    }
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 10px;
        width: 40%;
        text-align: left;
        font-weight: 700;
        font-size: 10px;
        color: #A04657;
    }
    .modern-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #eef2f6;
        border-radius: 10px;
        overflow: hidden;
    }
}

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

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

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

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

<script>
// Table search functionality
document.getElementById('tableSearch')?.addEventListener('keyup', function() {
    let searchValue = this.value.toLowerCase().trim();
    let rows = document.querySelectorAll('#shiftsTable tbody tr');
    
    rows.forEach(row => {
        if (row.querySelector('.empty-state')) {
            return;
        }
        let text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchValue) ? '' : 'none';
    });
});

// Auto-hide alerts after 5 seconds
document.querySelectorAll('.alert-custom').forEach(alert => {
    setTimeout(() => {
        if (alert) alert.style.opacity = '0';
        setTimeout(() => {
            if (alert) alert.remove();
        }, 300);
    }, 5000);
});
</script>

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