<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Includes/helpers.php'; // getStatusInfo fonksiyonu için
use HatiApp\Core\Database;

$db = new Database();
$conn = $db->getConnection();
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';

// Mevcut ay ve yılı belirle
$current_month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$current_year = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Ayın gün sayısını al
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $current_month, $current_year);

// Önceki ve sonraki ay/yıl hesaplamaları
$prev_month_ts = strtotime("-1 month", strtotime($current_year . "-" . $current_month . "-01"));
$next_month_ts = strtotime("+1 month", strtotime($current_year . "-" . $current_month . "-01"));

$prev_month = date('m', $prev_month_ts);
$prev_year = date('Y', $prev_month_ts);
$next_month = date('m', $next_month_ts);
$next_year = date('Y', $next_month_ts);

$personnel_list = [];
$puantaj_data = [];
$overtime_data = [];

// Form gönderildiğinde veritabanına kaydetme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save_puantaj' && isset($_POST['personnel_puantaj'])) {
        $conn->beginTransaction();
        try {
            foreach ($_POST['personnel_puantaj'] as $personnel_id => $daily_hours) {
                foreach ($daily_hours as $day => $hours) {
                    $work_date = $current_year . '-' . str_pad($current_month, 2, '0', STR_PAD_LEFT) . '-' . str_pad($day, 2, '0', STR_PAD_LEFT);
                    $hours = (float)$hours;

                    // Eğer veri varsa güncelle, yoksa ekle
                    $stmt_check = $conn->prepare("SELECT id FROM personnel_puantaj WHERE personnel_id = ? AND work_date = ?");
                    $stmt_check->execute([$personnel_id, $work_date]);
                    $existing_record = $stmt_check->fetch(PDO::FETCH_ASSOC);

                    if ($existing_record) {
                        $stmt_update = $conn->prepare("UPDATE personnel_puantaj SET work_hours = ? WHERE id = ?");
                        $stmt_update->execute([$hours, $existing_record['id']]);
                    } else {
                        $stmt_insert = $conn->prepare("INSERT INTO personnel_puantaj (personnel_id, work_date, work_hours, notes) VALUES (?, ?, ?, ?)");
                        $stmt_insert->execute([$personnel_id, $work_date, $hours, 'Manuel giriş']);
                    }
                }
            }
            $conn->commit();
            $message = 'Puantaj başarıyla kaydedildi!';
            $message_type = 'success';
        } catch (PDOException $e) {
            $conn->rollBack();
            $message = 'Puantaj kaydı sırasında hata oluştu: ' . $e->getMessage();
            $message_type = 'error';
        }
    } elseif ($_POST['action'] === 'save_overtime' && isset($_POST['personnel_overtime'])) {
        $conn->beginTransaction();
        try {
            foreach ($_POST['personnel_overtime'] as $personnel_id => $daily_overtime_hours) {
                foreach ($daily_overtime_hours as $day => $hours) {
                    $overtime_date = $current_year . '-' . str_pad($current_month, 2, '0', STR_PAD_LEFT) . '-' . str_pad($day, 2, '0', STR_PAD_LEFT);
                    $hours = (float)$hours;

                    // Eğer veri varsa güncelle, yoksa ekle
                    $stmt_check = $conn->prepare("SELECT id FROM personnel_overtime WHERE personnel_id = ? AND overtime_date = ?");
                    $stmt_check->execute([$personnel_id, $overtime_date]);
                    $existing_record = $stmt_check->fetch(PDO::FETCH_ASSOC);

                    if ($existing_record) {
                        $stmt_update = $conn->prepare("UPDATE personnel_overtime SET overtime_hours = ? WHERE id = ?");
                        $stmt_update->execute([$hours, $existing_record['id']]);
                    } else {
                        $stmt_insert = $conn->prepare("INSERT INTO personnel_overtime (personnel_id, overtime_date, overtime_hours, notes) VALUES (?, ?, ?, ?)");
                        $stmt_insert->execute([$personnel_id, $overtime_date, $hours, 'Manuel fazla mesai']);
                    }
                }
            }
            $conn->commit();
            $message = 'Fazla mesai başarıyla kaydedildi!';
            $message_type = 'success';
        } catch (PDOException $e) {
            $conn->rollBack();
            $message = 'Fazla mesai kaydı sırasında hata oluştu: ' . $e->getMessage();
            $message_type = 'error';
        }
    }
    // Yönlendirme ve mesajı göster
    header("Location: puantaj.php?month=$current_month&year=$current_year&status=$message_type&message=" . urlencode($message));
    exit;
}


// Personel listesini çek
try {
    $stmt_personnel = $conn->prepare("SELECT id, full_name, title FROM personnel ORDER BY full_name ASC");
    $stmt_personnel->execute();
    $personnel_list = $stmt_personnel->fetchAll(PDO::FETCH_ASSOC);

    // Seçilen aya ait puantaj verilerini çek
    $stmt_puantaj = $conn->prepare("SELECT personnel_id, DAY(work_date) as day, work_hours FROM personnel_puantaj WHERE YEAR(work_date) = ? AND MONTH(work_date) = ?");
    $stmt_puantaj->execute([$current_year, $current_month]);
    foreach ($stmt_puantaj->fetchAll(PDO::FETCH_ASSOC) as $record) {
        $puantaj_data[$record['personnel_id']][$record['day']] = $record['work_hours'];
    }

    // Seçilen aya ait fazla mesai verilerini çek
    $stmt_overtime = $conn->prepare("SELECT personnel_id, DAY(overtime_date) as day, overtime_hours FROM personnel_overtime WHERE YEAR(overtime_date) = ? AND MONTH(overtime_date) = ?");
    $stmt_overtime->execute([$current_year, $current_month]);
    foreach ($stmt_overtime->fetchAll(PDO::FETCH_ASSOC) as $record) {
        $overtime_data[$record['personnel_id']][$record['day']] = $record['overtime_hours'];
    }

} catch (PDOException $e) {
    die("Hata: " . $e->getMessage());
}

$month_names_tr = [
    1 => 'Ocak', 2 => 'Şubat', 3 => 'Mart', 4 => 'Nisan', 5 => 'Mayıs', 6 => 'Haziran',
    7 => 'Temmuz', 8 => 'Ağustos', 9 => 'Eylül', 10 => 'Ekim', 11 => 'Kasım', 12 => 'Aralık'
];

?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Puantaj</title>
    <link rel="stylesheet" href="css/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        /* Puantaj ve Fazla Mesai Tabloları için Stil */
        .puantaj-container {
            padding: 20px;
        }

        .puantaj-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            background-color: #f8f9fa;
            padding: 10px 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,.05);
        }

        .puantaj-header h2 {
            margin: 0;
            color: #343a40;
        }

        .month-selector a {
            text-decoration: none;
            color: var(--primary);
            font-weight: bold;
            margin: 0 10px;
            padding: 5px 10px;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }
        .month-selector a:hover {
            background-color: #e9ecef;
        }
        .month-selector span {
            font-weight: bold;
            color: #495057;
        }
        
        .puantaj-table-wrapper {
            overflow-x: auto; /* Yatay kaydırma çubuğu */
            margin-bottom: 30px;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0,0,0,.05);
        }

        .puantaj-table-wrapper table {
            width: 100%; /* Tablonun genişliği */
            min-width: fit-content; /* İçeriğe göre minimum genişlik */
            border-collapse: collapse;
            font-size: 14px;
        }

        .puantaj-table-wrapper th,
        .puantaj-table-wrapper td {
            border: 1px solid #dee2e6;
            padding: 8px;
            text-align: center;
            white-space: nowrap; /* Hücre içeriğinin tek satırda kalmasını sağlar */
        }

        .puantaj-table-wrapper th {
            background-color: #e9ecef;
            font-weight: bold;
            color: #495057;
        }
        
        .puantaj-table-wrapper tbody tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        .puantaj-table-wrapper tbody tr:hover {
            background-color: #e9f5fd;
        }

        .puantaj-table-wrapper td:first-child { /* Personel sütunu */
            text-align: left;
            min-width: 180px; /* Personel adları için daha geniş alan */
            max-width: 250px;
            position: sticky; /* Sütunu sabitle */
            left: 0;
            background-color: inherit; /* Kaydırma yaparken arka plan rengi */
            z-index: 2; /* Diğer hücrelerin üstünde olmasını sağla */
        }
        .puantaj-table-wrapper thead th:first-child { /* Personel başlık sütunu */
            position: sticky;
            left: 0;
            z-index: 3; /* Daha yüksek z-index */
        }
        /* Toplam ve İmza sütunlarını sabitleme */
        .puantaj-table-wrapper th:last-child,
        .puantaj-table-wrapper td:last-child {
            position: sticky;
            right: 0;
            background-color: #e9ecef; /* Başlık için */
            z-index: 2;
        }
        .puantaj-table-wrapper td:last-child {
            background-color: inherit; /* Kaydırma yaparken arka plan rengi */
            font-weight: bold;
        }


        .puantaj-table-wrapper input[type="number"] {
            width: 40px;
            padding: 4px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            text-align: center;
            font-size: 13px;
        }
        
        /* Özel gün renklendirmesi (Görseldeki gibi) */
        .holiday-day { /* Kırmızı gün */
            background-color: #ffe0e0;
            color: #dc3545;
            font-weight: bold;
        }
        .special-day { /* Mavi gün */
            background-color: #e0f7fa;
            color: #007bff;
            font-weight: bold;
        }

        /* Personel adı ve unvanı */
        .personnel-info {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .personnel-info svg {
            color: #6c757d;
        }
        .personnel-info div {
            text-align: left;
        }
        .personnel-info .name {
            font-weight: bold;
            color: #343a40;
        }
        .personnel-info .title {
            font-size: 12px;
            color: #6c757d;
        }

        .form-actions {
            text-align: right;
            margin-top: 20px;
        }
        .form-actions button {
            background-color: var(--primary);
            color: white;
            border: none;
            padding: 10px 25px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
        }
        .form-actions button:hover {
            background-color: var(--primary-dark);
        }
    </style>
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>

<div class="puantaj-container">
    <div class="puantaj-header">
        <a href="puantaj.php?month=<?php echo $prev_month; ?>&year=<?php echo $prev_year; ?>" class="month-selector">&lt; Önceki Ay</a>
        <h2><?php echo $month_names_tr[$current_month] . ' ' . $current_year; ?> Puantaj Tablosu</h2>
        <a href="puantaj.php?month=<?php echo $next_month; ?>&year=<?php echo $next_year; ?>" class="month-selector">Sonraki Ay &gt;</a>
    </div>

    <?php if ($message): ?>
        <p class="message" style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
            <?php echo htmlspecialchars($message); ?>
        </p>
    <?php endif; ?>

    <div class="detail-box puantaj-table-wrapper">
        <form action="puantaj.php?month=<?php echo $current_month; ?>&year=<?php echo $current_year; ?>" method="POST">
            <input type="hidden" name="action" value="save_puantaj">
            <table>
                <thead>
                    <tr>
                        <th rowspan="2">Personel</th>
                        <th colspan="<?php echo $days_in_month; ?>">Çalışılan Günler</th>
                        <th rowspan="2">Çalıştığı Toplam Saat</th>
                    </tr>
                    <tr>
                        <?php 
                        for ($i = 1; $i <= $days_in_month; $i++):
                            $day_of_week = date('N', strtotime($current_year . '-' . $current_month . '-' . $i)); // 1 (Pazartesi) - 7 (Pazar)
                            $class = '';
                            if ($day_of_week == 6 || $day_of_week == 7) { // Cumartesi veya Pazar
                                $class = 'holiday-day';
                            }
                            // Görseldeki gibi 12, 13, 14, 19, 26, 27, 28, 29, 30, 31 tarihlerini mavi yapalım (örnek olarak)
                            if (in_array($i, [12, 13, 14, 19, 26, 27, 28, 29, 30, 31])) {
                                $class = 'special-day';
                            }
                        ?>
                            <th class="<?php echo $class; ?>"><?php echo $i; ?></th>
                        <?php endfor; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($personnel_list as $p): ?>
                    <tr>
                        <td class="personnel-info">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 256 256"><path d="M128,128a8,8,0,1,1-8-8A8,8,0,0,1,128,128Zm0-32a8,8,0,1,0-8-8A8,8,0,0,0,128,96Zm0,64a8,8,0,1,0-8-8A8,8,0,0,0,128,160Zm-40,0a8,8,0,1,0-8-8A8,8,0,0,0,88,160Zm0-32a8,8,0,1,0-8-8A8,8,0,0,0,88,128Zm0-32a8,8,0,1,0-8-8A8,8,0,0,0,88,96Zm80,64a8,8,0,1,0-8-8A8,8,0,0,0,168,160Zm0-32a8,8,0,1,0-8-8A8,8,0,0,0,168,128Zm0-32a8,8,0,1,0-8-8A8,8,0,0,0,168,96Z"></path></svg>
                            <div>
                                <div class="name"><?php echo htmlspecialchars($p['full_name']); ?></div>
                                <div class="title"><?php echo htmlspecialchars($p['title'] ?? '-'); ?></div>
                            </div>
                        </td>
                        <?php 
                        $total_work_hours = 0;
                        for ($i = 1; $i <= $days_in_month; $i++):
                            $work_date_str = $current_year . '-' . str_pad($current_month, 2, '0', STR_PAD_LEFT) . '-' . str_pad($i, 2, '0', STR_PAD_LEFT);
                            $day_of_week = date('N', strtotime($work_date_str)); // 1 (Pazartesi) - 7 (Pazar)
                            $cell_class = '';
                            if ($day_of_week == 6 || $day_of_week == 7) {
                                $cell_class = 'holiday-day';
                            }
                            if (in_array($i, [12, 13, 14, 19, 26, 27, 28, 29, 30, 31])) {
                                $cell_class = 'special-day';
                            }

                            $hours = $puantaj_data[$p['id']][$i] ?? 0;
                            $total_work_hours += $hours;
                        ?>
                            <td class="<?php echo $cell_class; ?>">
                                <input type="number" name="personnel_puantaj[<?php echo $p['id']; ?>][<?php echo $i; ?>]" 
                                       value="<?php echo $hours; ?>" min="0" max="12" step="0.5">
                            </td>
                        <?php endfor; ?>
                        <td><?php echo number_format($total_work_hours, 1); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div class="form-actions">
                <button type="submit">Kaydet</button>
            </div>
        </form>
    </div>

    <h3 class="detail-box-title" style="margin-top: 40px;">Fazla Mesai Tablosu</h3>
    <div class="detail-box puantaj-table-wrapper">
        <form action="puantaj.php?month=<?php echo $current_month; ?>&year=<?php echo $current_year; ?>" method="POST">
            <input type="hidden" name="action" value="save_overtime">
            <table>
                <thead>
                    <tr>
                        <th rowspan="2">Personel</th>
                        <th colspan="<?php echo $days_in_month; ?>">Fazla Mesai Saatleri</th>
                        <th rowspan="2">Toplam Fazla Mesai Saati</th>
                    </tr>
                    <tr>
                        <?php 
                        for ($i = 1; $i <= $days_in_month; $i++): 
                            $day_of_week = date('N', strtotime($current_year . '-' . $current_month . '-' . $i)); // 1 (Pazartesi) - 7 (Pazar)
                            $class = '';
                            if ($day_of_week == 6 || $day_of_week == 7) { // Cumartesi veya Pazar
                                $class = 'holiday-day';
                            }
                            if (in_array($i, [12, 13, 14, 19, 26, 27, 28, 29, 30, 31])) {
                                $class = 'special-day';
                            }
                        ?>
                            <th class="<?php echo $class; ?>"><?php echo $i; ?></th>
                        <?php endfor; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($personnel_list as $p): ?>
                    <tr>
                        <td class="personnel-info">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 256 256"><path d="M128,128a8,8,0,1,1-8-8A8,8,0,0,1,128,128Zm0-32a8,8,0,1,0-8-8A8,8,0,0,0,128,96Zm0,64a8,8,0,1,0-8-8A8,8,0,0,0,128,160Zm-40,0a8,8,0,1,0-8-8A8,8,0,0,0,88,160Zm0-32a8,8,0,1,0-8-8A8,8,0,0,0,88,128Zm0-32a8,8,0,1,0-8-8A8,8,0,0,0,88,96Zm80,64a8,8,0,1,0-8-8A8,8,0,0,0,168,160Zm0-32a8,8,0,1,0-8-8A8,8,0,0,0,168,128Zm0-32a8,8,0,1,0-8-8A8,8,0,0,0,168,96Z"></path></svg>
                            <div>
                                <div class="name"><?php echo htmlspecialchars($p['full_name']); ?></div>
                                <div class="title"><?php echo htmlspecialchars($p['title'] ?? '-'); ?></div>
                            </div>
                        </td>
                        <?php 
                        $total_overtime_hours = 0;
                        for ($i = 1; $i <= $days_in_month; $i++):
                            $overtime_date_str = $current_year . '-' . str_pad($current_month, 2, '0', STR_PAD_LEFT) . '-' . str_pad($i, 2, '0', STR_PAD_LEFT);
                            $day_of_week = date('N', strtotime($overtime_date_str)); // 1 (Pazartesi) - 7 (Pazar)
                            $cell_class = '';
                            if ($day_of_week == 6 || $day_of_week == 7) {
                                $cell_class = 'holiday-day';
                            }
                            if (in_array($i, [12, 13, 14, 19, 26, 27, 28, 29, 30, 31])) {
                                $cell_class = 'special-day';
                            }

                            $hours = $overtime_data[$p['id']][$i] ?? 0;
                            $total_overtime_hours += $hours;
                        ?>
                            <td class="<?php echo $cell_class; ?>">
                                <input type="number" name="personnel_overtime[<?php echo $p['id']; ?>][<?php echo $i; ?>]" 
                                       value="<?php echo $hours; ?>" min="0" max="12" step="0.5">
                            </td>
                        <?php endfor; ?>
                        <td><?php echo number_format($total_overtime_hours, 1); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div class="form-actions" style="margin-top: 20px;">
                <button type="submit">Kaydet</button>
            </div>
        </form>
    </div>
</div>
</body>
</html>