<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'includes/translation.php';

if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

$page_title = __('pharmacist_schedule_bulk_page') . ' - ' . __('system_name');

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

$message = '';
$error = '';

// معالجة الإدخال الجماعي
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['bulk_schedule'])) {
    try {
        $conn->beginTransaction();
        
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        
        // حساب عدد الأيام
        $start_dt = new DateTime($start_date);
        $end_dt = new DateTime($end_date);
        $interval = $start_dt->diff($end_dt);
        $total_days = $interval->days + 1;
        
        foreach ($_POST['schedules'] as $pharmacist_id => $days) {
            $current_date = clone $start_dt;
            for ($day = 1; $day <= $total_days; $day++) {
                if (isset($days[$day]) && !empty($days[$day]) && $days[$day] != '-') {
                    $date = $current_date->format('Y-m-d');
                    
                    // حذف الجدول القديم إن وجد
                    $delete_stmt = $conn->prepare("DELETE FROM pharmacist_schedule WHERE pharmacist_id = ? AND schedule_date = ? AND team = ?");
                    $delete_stmt->execute([$pharmacist_id, $date, $_POST['team']]);
                    
                    // إدخال الجدول الجديد
                    $insert_stmt = $conn->prepare("INSERT INTO pharmacist_schedule (pharmacist_id, team, schedule_date, shift_time, created_by) VALUES (?, ?, ?, ?, ?)");
                    $insert_stmt->execute([$pharmacist_id, $_POST['team'], $date, $days[$day], $_SESSION['user_id']]);
                }
                $current_date->modify('+1 day');
            }
        }
        
        $conn->commit();
        $message = __('schedule_saved_successfully');
        
    } catch (PDOException $e) {
        $conn->rollBack();
        $error = __('error_occurred') . ": " . $e->getMessage();
    }
}

// جلب الصيادلة
try {
    $pharmacists_stmt = $conn->query("SELECT * FROM pharmacists WHERE is_active = 1 ORDER BY name");
    $pharmacists = $pharmacists_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $pharmacists = [];
}

// حساب التواريخ الافتراضية
$current_month = date('m');
$current_year = date('Y');
$prev_month = $current_month - 1;
$prev_year = $current_year;
if ($prev_month == 0) {
    $prev_month = 12;
    $prev_year = $current_year - 1;
}
$default_start = "$prev_year-" . str_pad($prev_month, 2, '0', STR_PAD_LEFT) . "-21";
$default_end = "$current_year-" . str_pad($current_month, 2, '0', STR_PAD_LEFT) . "-20";

// حساب عدد الأيام للجدول
if (isset($_GET['start_date']) && isset($_GET['end_date'])) {
    $start_date = $_GET['start_date'];
    $end_date = $_GET['end_date'];
} else {
    $start_date = $default_start;
    $end_date = $default_end;
}

$start_dt = new DateTime($start_date);
$end_dt = new DateTime($end_date);
$interval = $start_dt->diff($end_dt);
$total_days = $interval->days + 1;

include 'includes/header.php';
?>

<style>
.bulk-entry-table {
    width: 100%;
    border-collapse: collapse;
    background: white;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.bulk-entry-table th {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 10px 5px;
    text-align: center;
    font-size: 0.8rem;
    border: 1px solid #dee2e6;
    position: sticky;
    top: 0;
    z-index: 10;
}

.bulk-entry-table td {
    padding: 5px;
    text-align: center;
    border: 1px solid #dee2e6;
}

.bulk-entry-table input[type="text"] {
    width: 100%;
    border: 1px solid #ced4da;
    border-radius: 4px;
    padding: 4px;
    text-align: center;
    font-size: 0.85rem;
}

.bulk-entry-table input[type="text"]:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.pharmacist-name {
    font-weight: 600;
    text-align: right;
    padding-right: 10px !important;
}

.quick-fill-btn {
    padding: 2px 8px;
    font-size: 0.75rem;
    border-radius: 4px;
    margin: 0 2px;
}

.table-container {
    max-height: 70vh;
    overflow-y: auto;
    position: relative;
}
</style>


    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0" style="color: #667eea;">
                <i class="fas fa-calendar-plus me-2"></i>
                <?php echo __('bulk_schedule_entry'); ?>
            </h1>
            <p class="text-muted mb-0"><?php echo __('enter_full_month_schedule'); ?></p>
        </div>
        <div>
            <a href="pharmacist_schedule.php" class="btn btn-outline-secondary">
                <i class="fas fa-eye me-2"></i> <?php echo __('view_schedule'); ?>
            </a>
        </div>
    </div>

    <?php if (!empty($message)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle me-2"></i>
            <?php echo $message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (!empty($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-circle me-2"></i>
            <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-body">
            <form method="POST" id="bulkScheduleForm">
                <input type="hidden" name="bulk_schedule" value="1">
                <input type="hidden" name="start_date" value="<?php echo $start_date; ?>">
                <input type="hidden" name="end_date" value="<?php echo $end_date; ?>">
                
                <div class="row mb-4">
                    <div class="col-md-3">
                        <label for="team" class="form-label"><?php echo __('team'); ?></label>
                        <select class="form-select" id="team" name="team" required>
                            <option value=""><?php echo __('select_team'); ?></option>
                            <option value="OR Team">OR Team</option>
                            <option value="Ward Team">Ward Team</option>
                            <option value="ICU Team">ICU Team</option>
                            <option value="NICU Team">NICU Team</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="start_date" class="form-label"><?php echo __('from_date'); ?></label>
                        <input type="date" class="form-control" id="start_date" name="start_date_display" value="<?php echo $start_date; ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label for="end_date" class="form-label"><?php echo __('to_date'); ?></label>
                        <input type="date" class="form-control" id="end_date" name="end_date_display" value="<?php echo $end_date; ?>" required>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="button" class="btn btn-info w-100" onclick="updateTable()">
                            <i class="fas fa-sync me-2"></i> <?php echo __('update_table'); ?>
                        </button>
                    </div>
                </div>

                <div class="mb-3">
                    <strong><?php echo __('quick_fill'); ?>:</strong>
                    <button type="button" class="btn btn-sm btn-warning quick-fill-btn" onclick="quickFill('L')">L (12h)</button>
                    <button type="button" class="btn btn-sm btn-danger quick-fill-btn" onclick="quickFill('N')">N (12h)</button>
                    <button type="button" class="btn btn-sm btn-info quick-fill-btn" onclick="quickFill('A')">A (8h)</button>
                    <button type="button" class="btn btn-sm btn-primary quick-fill-btn" onclick="quickFill('E')">E (8h)</button>
                    <button type="button" class="btn btn-sm btn-secondary quick-fill-btn" onclick="quickFill('C')">C (7h)</button>
                    <button type="button" class="btn btn-sm btn-secondary quick-fill-btn" onclick="quickFill('')"><?php echo __('clear'); ?></button>
                    <span class="ms-3 text-muted"><?php echo __('select_cell_then_click'); ?></span>
                </div>

                <div class="table-container">
                    <table class="bulk-entry-table">
                        <thead>
                            <tr>
                                <th><?php echo __('pharmacist_name'); ?></th>
                                <?php 
                                $current_date = clone $start_dt;
                                for ($d = 1; $d <= $total_days; $d++): 
                                    echo "<th>" . $current_date->format('j') . "<br><small>" . $current_date->format('M') . "</small></th>";
                                    $current_date->modify('+1 day');
                                endfor; 
                                ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($pharmacists as $pharmacist): ?>
                            <tr>
                                <td class="pharmacist-name">
                                    <?php echo htmlspecialchars($pharmacist['name']); ?>
                                    <?php if ($pharmacist['code']): ?>
                                        <small class="text-muted">(<?php echo htmlspecialchars($pharmacist['code']); ?>)</small>
                                    <?php endif; ?>
                                </td>
                                <?php for ($d = 1; $d <= $total_days; $d++): ?>
                                    <td>
                                        <input 
                                            type="text" 
                                            name="schedules[<?php echo $pharmacist['id']; ?>][<?php echo $d; ?>]" 
                                            maxlength="1"
                                            placeholder="-"
                                            onclick="selectCell(this)"
                                        >
                                    </td>
                                <?php endfor; ?>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="mt-4 p-3" style="background-color: #f8f9fa; border-radius: 8px;">
                    <p class="mb-2"><strong><?php echo __('legend'); ?>:</strong></p>
                    <div class="row">
                        <div class="col-md-12">
                            <p class="mb-1"><span class="badge bg-warning text-dark">L</span> = <?php echo __('long_day'); ?> (8am-8pm) - 12 hours</p>
                            <p class="mb-1"><span class="badge bg-danger">N</span> = <?php echo __('night_shift'); ?> (8pm-8am) - 12 hours</p>
                            <p class="mb-1"><span class="badge bg-info">A</span> = <?php echo __('morning_shift'); ?> (8am-4pm) - 8 hours</p>
                            <p class="mb-1"><span class="badge bg-primary">E</span> = <?php echo __('evening_shift'); ?> (4pm-12am) - 8 hours</p>
                            <p class="mb-1"><span class="badge bg-secondary">C</span> = <?php echo __('coverage'); ?> (8am-3pm) - 7 hours</p>
                        </div>
                    </div>
                </div>

                <div class="text-center mt-4">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="fas fa-save me-2"></i> <?php echo __('save_schedule'); ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
let selectedCell = null;

function selectCell(input) {
    if (selectedCell) {
        selectedCell.style.backgroundColor = '';
    }
    selectedCell = input;
    selectedCell.style.backgroundColor = '#ffffcc';
}

function quickFill(value) {
    if (selectedCell) {
        selectedCell.value = value;
        // Move to next cell
        let nextInput = selectedCell.parentElement.nextElementSibling?.querySelector('input');
        if (nextInput) {
            selectCell(nextInput);
            nextInput.focus();
        }
    }
}

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    if (selectedCell) {
        if (e.key === 'l' || e.key === 'L') {
            e.preventDefault();
            quickFill('L');
        } else if (e.key === 'a' || e.key === 'A') {
            e.preventDefault();
            quickFill('A');
        } else if (e.key === 'e' || e.key === 'E') {
            e.preventDefault();
            quickFill('E');
        } else if (e.key === 'n' || e.key === 'N') {
            e.preventDefault();
            quickFill('N');
        } else if (e.key === 'c' || e.key === 'C') {
            e.preventDefault();
            quickFill('C');
        } else if (e.key === 'Delete' || e.key === 'Backspace') {
            selectedCell.value = '';
        }
    }
});

function updateTable() {
    const startDate = document.getElementById('start_date').value;
    const endDate = document.getElementById('end_date').value;
    
    if (startDate && endDate) {
        window.location.href = '?start_date=' + startDate + '&end_date=' + endDate;
    } else {
        alert('<?php echo __('please_select_dates'); ?>');
    }
}
</script>

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

