<?php
/**
 * Simple Leave Application Form
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

$pageTitle = 'Apply for Leave';
$currentModule = 'leave';

$siteId = getCurrentSiteId();
$errors = [];
$success = '';

// Get employees list
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT e.employee_id, e.employee_code, 
               CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as full_name
        FROM employees e
        WHERE e.site_id = ? AND e.employment_status = 'active'
        ORDER BY e.first_name
    ");
    $stmt->execute([$siteId]);
    $employees = $stmt->fetchAll();
} catch (Exception $e) {
    $employees = [];
}

// Get leave types
try {
    $stmt = $db->prepare("
        SELECT leave_type_id, leave_type_name
        FROM leave_types 
        WHERE site_id = ? AND leave_type_status = 'active'
        ORDER BY leave_type_name
    ");
    $stmt->execute([$siteId]);
    $leaveTypes = $stmt->fetchAll();
} catch (Exception $e) {
    $leaveTypes = [];
}

// Get site name
try {
    $stmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $site = $stmt->fetch();
    $siteName = $site['site_name'] ?? 'Company';
} catch (Exception $e) {
    $siteName = 'Company';
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $employee_id = isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0;
    $leave_type_id = isset($_POST['leave_type_id']) ? (int)$_POST['leave_type_id'] : 0;
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';
    $reason = trim($_POST['reason'] ?? '');
    
    // Validation
    if ($employee_id <= 0) {
        $errors[] = 'Please select an employee.';
    }
    
    if ($leave_type_id <= 0) {
        $errors[] = 'Please select leave type.';
    }
    
    if (empty($start_date)) {
        $errors[] = 'Start date is required.';
    }
    
    if (empty($end_date)) {
        $errors[] = 'End date is required.';
    }
    
    if (!empty($start_date) && !empty($end_date) && $start_date > $end_date) {
        $errors[] = 'End date must be after start date.';
    }
    
    // If no errors, save to database
    if (empty($errors)) {
        try {
            $userId = getCurrentUserId();
            
            // Calculate total days
            $start = new DateTime($start_date);
            $end = new DateTime($end_date);
            $totalDays = $start->diff($end)->days + 1;
            
            $sql = "
                INSERT INTO leave_applications (
                    site_id, employee_id, leave_type_id, start_date, end_date,
                    total_days, reason, application_status, applied_by
                ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)
            ";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $siteId,
                $employee_id,
                $leave_type_id,
                $start_date,
                $end_date,
                $totalDays,
                $reason ?: null,
                $userId
            ]);
            
            $leaveApplicationId = $db->lastInsertId();
            
            // Send notifications to branch Admin and HR users
            notifyBranchAdminHRForLeave($siteId, $employee_id, $leaveApplicationId, $leave_type_id, $start_date, $end_date, $totalDays);
            
            redirect(BASE_URL . '/modules/leave/list.php', 'Leave application submitted successfully.');
            
        } catch (Exception $e) {
            error_log("Error creating leave application: " . $e->getMessage());
            $errors[] = 'An error occurred. Please try again.';
        }
    }
}

include __DIR__ . '/../../includes/header.php';
?>

<style>
/* Base Styles */
.leave-form {
    max-width: 700px;
    margin: 0 auto;
    background: white;
    border: 2px solid #1e40af;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.leave-form-header {
    text-align: center;
    padding: 20px;
    font-size: 22px;
    font-weight: bold;
    color: #1e40af;
    border-bottom: 3px solid #1e40af;
}

.leave-form-title {
    background: #1e40af;
    color: white;
    padding: 12px 20px;
    font-weight: bold;
    font-size: 16px;
}

.leave-form-body {
    padding: 25px 30px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
    font-size: 14px;
}

.form-group label span.required {
    color: #ef4444;
}

.form-group select,
.form-group input[type="date"],
.form-group input[type="text"],
.form-group textarea {
    width: 100%;
    padding: 12px 14px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 16px;
    transition: border-color 0.2s;
    box-sizing: border-box;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    background-color: #fff;
}

.form-group select {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23333' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 12px center;
    padding-right: 36px;
}

.form-group select:focus,
.form-group input:focus,
.form-group textarea:focus {
    outline: none;
    border-color: #1e40af;
    box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.1);
}

.form-group textarea {
    min-height: 100px;
    resize: vertical;
}

.dates-row {
    display: flex;
    gap: 20px;
}

.dates-row .form-group {
    flex: 1;
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 20px 30px;
    background: #f9fafb;
    border-top: 1px solid #e5e7eb;
    flex-wrap: wrap;
}

.btn {
    padding: 12px 24px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
    border: none;
    text-align: center;
    transition: all 0.2s ease;
}

.btn-primary {
    background: #1e40af;
    color: white;
}

.btn-primary:hover {
    background: #1e3a8a;
    transform: translateY(-1px);
}

.btn-secondary {
    background: #e5e7eb;
    color: #374151;
}

.btn-secondary:hover {
    background: #d1d5db;
}

.alert {
    padding: 12px 16px;
    border-radius: 6px;
    margin: 15px 20px;
}

.alert-error {
    background: #fee2e2;
    border: 1px solid #ef4444;
    color: #991b1b;
}

.alert-error ul {
    margin: 0;
    padding-left: 20px;
}

.alert-warning {
    background: #fef3c7;
    border: 1px solid #f59e0b;
    color: #92400e;
}

.no-leave-types {
    text-align: center;
    padding: 30px;
    color: #666;
}

/* ========== RESPONSIVE STYLES ========== */

/* Tablet (768px and below) */
@media screen and (max-width: 768px) {
    .leave-form {
        margin: 10px;
        max-width: 100%;
        border-radius: 6px;
    }
    
    .leave-form-header {
        padding: 15px;
        font-size: 18px;
    }
    
    .leave-form-title {
        padding: 10px 15px;
        font-size: 14px;
    }
    
    .leave-form-body {
        padding: 20px 15px;
    }
    
    .dates-row {
        flex-direction: column;
        gap: 0;
    }
    
    .dates-row .form-group {
        width: 100%;
    }
    
    .form-actions {
        padding: 15px;
        justify-content: center;
    }
    
    .btn {
        padding: 12px 20px;
        font-size: 14px;
    }
    
    .alert {
        margin: 10px 15px;
        font-size: 13px;
    }
}

/* Mobile (480px and below) */
@media screen and (max-width: 480px) {
    .leave-form {
        margin: 5px;
        border-width: 1px;
        border-radius: 4px;
    }
    
    .leave-form-header {
        padding: 12px 10px;
        font-size: 16px;
        border-bottom-width: 2px;
    }
    
    .leave-form-title {
        padding: 10px 12px;
        font-size: 13px;
    }
    
    .leave-form-body {
        padding: 15px 12px;
    }
    
    .form-group {
        margin-bottom: 16px;
    }
    
    .form-group label {
        font-size: 13px;
        margin-bottom: 6px;
    }
    
    .form-group select,
    .form-group input[type="date"],
    .form-group input[type="text"],
    .form-group textarea {
        padding: 12px 10px;
        font-size: 16px; /* Prevents zoom on iOS */
        border-radius: 4px;
    }
    
    .form-group select {
        padding-right: 32px;
        background-position: right 10px center;
    }
    
    .form-group textarea {
        min-height: 80px;
    }
    
    .form-actions {
        flex-direction: column;
        padding: 12px;
        gap: 8px;
    }
    
    .btn {
        width: 100%;
        padding: 14px 20px;
        font-size: 15px;
    }
    
    .alert {
        margin: 10px;
        padding: 10px 12px;
        font-size: 12px;
    }
    
    .alert-error ul {
        padding-left: 16px;
    }
}

/* Small Mobile (360px and below) */
@media screen and (max-width: 360px) {
    .leave-form-header {
        font-size: 14px;
        padding: 10px 8px;
    }
    
    .leave-form-title {
        font-size: 12px;
        padding: 8px 10px;
    }
    
    .leave-form-body {
        padding: 12px 10px;
    }
    
    .form-group label {
        font-size: 12px;
    }
    
    .btn {
        font-size: 14px;
        padding: 12px 16px;
    }
}

/* Landscape orientation on mobile */
@media screen and (max-width: 768px) and (orientation: landscape) {
    .leave-form {
        margin: 10px auto;
        max-width: 90%;
    }
    
    .dates-row {
        flex-direction: row;
        gap: 15px;
    }
    
    .form-actions {
        flex-direction: row;
        justify-content: flex-end;
    }
    
    .btn {
        width: auto;
    }
}

/* Touch device optimizations */
@media (hover: none) and (pointer: coarse) {
    .form-group select,
    .form-group input[type="date"],
    .form-group input[type="text"],
    .form-group textarea {
        min-height: 48px;
    }
    
    .btn {
        min-height: 48px;
    }
}

/* Print styles */
@media print {
    .leave-form {
        border: 1px solid #000;
        box-shadow: none;
        max-width: 100%;
    }
    
    .form-actions {
        display: none;
    }
    
    .btn {
        display: none;
    }
}
</style>

<div class="leave-form">
    <div class="leave-form-header">
        <?php echo htmlspecialchars(strtoupper($siteName)); ?>
    </div>
    
    <div class="leave-form-title">
        Leave Application Form
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul>
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <?php if (empty($leaveTypes)): ?>
    <div class="alert alert-warning">
        <strong>⚠️ No leave types configured!</strong><br>
        Please ask admin to add leave types first.
        <?php if (hasPermission('SETTINGS_VIEW')): ?>
        <br><a href="<?php echo BASE_URL; ?>/admin/leave_types_create.php">+ Add Leave Types</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <form method="POST" action="">
        <div class="leave-form-body">
            <div class="form-group">
                <label>Employee <span class="required">*</span></label>
                <select name="employee_id" required>
                    <option value="">-- Select Employee --</option>
                    <?php foreach ($employees as $emp): ?>
                    <option value="<?php echo $emp['employee_id']; ?>" 
                            <?php echo (isset($_POST['employee_id']) && $_POST['employee_id'] == $emp['employee_id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($emp['employee_code'] . ' - ' . $emp['full_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label>Leave Type <span class="required">*</span></label>
                <select name="leave_type_id" required>
                    <option value="">-- Select Leave Type --</option>
                    <?php foreach ($leaveTypes as $type): ?>
                    <option value="<?php echo $type['leave_type_id']; ?>"
                            <?php echo (isset($_POST['leave_type_id']) && $_POST['leave_type_id'] == $type['leave_type_id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($type['leave_type_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="dates-row">
                <div class="form-group">
                    <label>Start Date <span class="required">*</span></label>
                    <input type="date" name="start_date" required 
                           value="<?php echo htmlspecialchars($_POST['start_date'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>End Date <span class="required">*</span></label>
                    <input type="date" name="end_date" required
                           value="<?php echo htmlspecialchars($_POST['end_date'] ?? ''); ?>">
                </div>
            </div>
            
            <div class="form-group">
                <label>Reason for Leave</label>
                <textarea name="reason" placeholder="Enter reason for leave (optional)..."><?php echo htmlspecialchars($_POST['reason'] ?? ''); ?></textarea>
            </div>
        </div>
        
        <div class="form-actions">
            <a href="<?php echo BASE_URL; ?>/modules/leave/list.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Submit Application</button>
        </div>
    </form>
</div>

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