<?php
ob_start();

// --- 1. ตรวจสอบการล็อกอิน ---
if (!isset($_COOKIE['kRlfYPpU_user_card_id']) || !isset($_COOKIE['kRlfYPpU_user_fname']) || !isset($_COOKIE['kRlfYPpU_user_br_id'])) {
    header('Location: index.php?reason=expired');
    exit;
}

$user_fname = $_COOKIE['kRlfYPpU_user_fname'];
$user_br_id = $_COOKIE['kRlfYPpU_user_br_id'];
$user_lname = $_COOKIE['kRlfYPpU_user_lname'] ?? '';
$user_nick = $_COOKIE['kRlfYPpU_user_nick'] ?? '';
$user_br_name = $_COOKIE['kRlfYPpU_user_br_name'] ?? '';
$user_szone_code = $_COOKIE['kRlfYPpU_user_szone_code'] ?? '';

// รับค่าเขตที่เลือก (ถ้าไม่มีใช้เขตของตัวเอง)
$selected_zone = isset($_GET['zone']) && $_GET['zone'] !== '' ? trim($_GET['zone']) : $user_szone_code;

// --- 2. ดึงข้อมูลกิจกรรม ---
$host_sqlsrv_1 = '192.168.10.61';
$db_config = 'CONFIG'; 
$user_sqlsrv_1 = 'zack';
$pass_sqlsrv_1 = 'zack123456';
$port_sqlsrv_1 = '1433';
$dsn_sqlsrv_config = "sqlsrv:Server=$host_sqlsrv_1,$port_sqlsrv_1;Database=$db_config;TrustServerCertificate=true";

$activities = [];
$db_error = false;

try {
    $conn_config = new PDO($dsn_sqlsrv_config, $user_sqlsrv_1, $pass_sqlsrv_1);
    $conn_config->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $today = new DateTime();
    $today_str = $today->format('Y-m-d');

    // --- ดึงข้อมูลตามเขตพนักงาน ---
    $sql_activities = "
        SELECT 
            a.APP_CODE, a.APP_NAME, a.APP_FDATE, a.APP_LDATE, a.APP_DATE, a.szone_code, a.BR_ID,
            ISNULL(b.BR_NAME, 'ไม่พบชื่อสาขา') AS BR_NAME,
            ISNULL(sz.staff_nick, '') AS zone_name
        FROM 
            CONFIG.dbo.APP_APPROVES AS a
        LEFT JOIN 
            EHONGDB.dbo.BRANCH AS b ON a.BR_ID = b.BR_ID
        LEFT JOIN
            EHONGDB.dbo.branch_salezone sz ON a.szone_code = sz.szone_code
        WHERE 
            (a.szone_code = ? OR a.szone_code = '99')
            AND DATEADD(day, -4, a.APP_FDATE) <= ?
            AND a.APP_LDATE >= ?
            AND a.APP_STATUS = '01'
        ORDER BY a.APP_FDATE DESC, a.APP_CODE ASC
    ";
    
    // --- ดึงรายชื่อเขตทั้งหมด + ชื่อเขต ---
    $sql_zones = "
        SELECT DISTINCT a.szone_code, ISNULL(sz.staff_nick, '') AS szone_name
        FROM CONFIG.dbo.APP_APPROVES a
        LEFT JOIN EHONGDB.dbo.branch_salezone sz ON a.szone_code = sz.szone_code
        WHERE a.APP_STATUS = '01'
        ORDER BY a.szone_code ASC
    ";
    $zones = $conn_config->query($sql_zones)->fetchAll(PDO::FETCH_ASSOC);

    // --- ดึงโครงการตามเขตที่เลือก ---
    $stmt_activities = $conn_config->prepare($sql_activities);
    $stmt_activities->execute([$selected_zone, $today_str, $today_str]); 
    $activities = $stmt_activities->fetchAll(PDO::FETCH_ASSOC);

    // ฟังก์ชันคำนวณวันเดินตลาด
    function calculateMarketWalkDates($fdate_str) {
        $fdate = new DateTime($fdate_str);
        $end_walk = clone $fdate;
        $end_walk->modify("-1 days");
        if ($end_walk->format('w') == '0') $end_walk->modify("-1 days");
        $days_to_sub = 3;
        for ($i = 1; $i <= 3; $i++) {
            $check = clone $fdate;
            $check->modify("-$i days");
            if ($check->format('w') == '0') { $days_to_sub = 4; break; }
        }
        $start_walk = clone $fdate;
        $start_walk->modify("-$days_to_sub days");
        return $start_walk->format('d/m') . ' - ' . $end_walk->format('d/m');
    }

} catch (PDOException $e) {
    error_log("Config DB Error: " . $e->getMessage());
    $db_error = true;
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>เลือกกิจกรรม</title>
    <link rel="icon" type="image/png" href="img/โลโก้กลม.png">
    <link rel="stylesheet" href="index.css?v=25.0"> 
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Kanit:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        .custom-select-wrapper { position: relative; width: 100%; z-index: 1000; }
        .custom-select-trigger {
            background: #fff; border: 2px solid #e2e8f0; border-radius: 4px;
            padding: 16px 40px 16px 48px; color: #0f172a; font-size: 0.9rem;
            cursor: pointer; display: flex; justify-content: space-between;
            align-items: center; transition: all 0.2s; text-align: left;
        }
        .custom-select-wrapper.open { z-index: 1001; }
        .custom-select-wrapper.open .custom-select-trigger {
            border-color: #DA1212;
            box-shadow: 0 0 0 4px rgba(218, 18, 18, 0.1);
            border-bottom-left-radius: 0; border-bottom-right-radius: 0;
        }
        .custom-options {
            position: absolute; top: 100%; left: 0; right: 0;
            background: #fff; border: 2px solid #DA1212; border-top: none;
            border-bottom-left-radius: 4px; border-bottom-right-radius: 4px;
            box-shadow: 0 20px 25px -5px rgba(0,0,0,0.2);
            z-index: 1001; max-height: 40vh; overflow-y: auto;
            display: none; list-style: none !important; padding: 0 !important; margin: 0 !important;
        }
        .custom-select-wrapper.open .custom-options { display: block !important; }
        .custom-option {
            padding: 14px 18px; border-bottom: 1px solid #f1f5f9;
            cursor: pointer; text-align: left; transition: background 0.2s;
            list-style: none !important;
        }
        .custom-option:last-child { border-bottom: none; }
        .custom-option:hover { background: #f8fafc; }
        .custom-option.selected { background: #fff5f5; border-left: 4px solid #DA1212; }
        
        .opt-zone { font-size: 0.75rem; color: #64748b; margin-bottom: 3px; }
        .opt-name { font-weight: 700; color: #DA1212; font-size: 0.95rem; margin-bottom: 4px; }
        .opt-dates { font-size: 0.75rem; color: #334155; line-height: 1.5; }
        .date-event { color: #f59e0b; font-weight: 600; }
        .date-walk { color: #10b981; font-weight: 600; }
        
        .custom-select-icon {
            position: absolute; left: 18px; top: 50%;
            transform: translateY(-50%); color: #DA1212; z-index: 2;
        }
        .arrow { font-size: 0.9rem; color: #94a3b8; transition: transform 0.3s; }
        .custom-select-wrapper.open .arrow { transform: rotate(180deg); }

        /* Unified style for zone select too */
        .zone-trigger { padding: 14px 40px 14px 48px; font-weight: 600; }
        .zone-option { padding: 12px 18px; font-weight: 500; color: #475569; }
        .zone-option.selected { color: #DA1212; font-weight: 700; }
    </style>
</head>
<body>
    <div class="background-overlay"></div>
    <div class="login-container">
        <div class="login-card">
            <div class="card-header">
                <img src="img/โลโก้กลม.png" alt="Logo" class="header-logo">
                <h1>ตรวจสอบรายชื่อโครงการ</h1>
                <p class="sub-title" style="line-height: 1.6;">
                    ยินดีต้อนรับคุณ <?php echo htmlspecialchars(trim(($_COOKIE['kRlfYPpU_user_barcode'] ?? $_COOKIE['kRlfYPpU_user_card_id']) . ' : ' . $user_fname . ' ' . $user_lname . ($user_nick ? " ($user_nick)" : ''))); ?><br>
                    <span style="font-size: 0.85em; opacity: 0.8;">สาขา: <?php echo htmlspecialchars($user_br_name); ?> | เขต: <?php echo htmlspecialchars($user_szone_code); ?></span>
                </p>
            </div>

            <form action="save_activity.php" method="post">
                
                <!-- เลือกเขต (Custom UI) -->
                <div class="input-group" style="position:relative; margin-bottom:14px;">
                    <i class="fas fa-map-marker-alt custom-select-icon"></i>
                    <div class="custom-select-wrapper" id="wrapper-zone">
                        <div class="custom-select-trigger zone-trigger">
                            <?php 
                                $current_zone_label = "เลือกเขต...";
                                foreach($zones as $z) {
                                    if($z['szone_code'] == $selected_zone) {
                                        $current_zone_label = "เขต " . $z['szone_code'] . " - " . ($z['szone_name'] ?: 'ไม่มีชื่อ');
                                        break;
                                    }
                                }
                            ?>
                            <span class="trigger-text"><?= htmlspecialchars($current_zone_label) ?></span>
                            <i class="fas fa-chevron-down arrow"></i>
                        </div>
                        <ul class="custom-options">
                            <?php foreach ($zones as $z): ?>
                                <li class="custom-option zone-option <?= ($z['szone_code'] == $selected_zone) ? 'selected' : '' ?>" data-zone="<?= htmlspecialchars($z['szone_code']) ?>">
                                    เขต <?= htmlspecialchars($z['szone_code']) ?> - <?= htmlspecialchars($z['szone_name'] ?: '') ?> <?= ($z['szone_code'] == $user_szone_code) ? ' (เขตของคุณ)' : '' ?>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>

                <!-- เลือกโครงการ (Custom UI) -->
                <div class="input-group" style="position:relative; margin-bottom: 24px;">
                    <i class="fas fa-list custom-select-icon"></i>
                    <div class="custom-select-wrapper" id="wrapper-activity">
                        <div class="custom-select-trigger">
                            <span class="trigger-text">-- เลือกโครงการที่นี่ --</span>
                            <i class="fas fa-chevron-down arrow"></i>
                        </div>
                        <ul class="custom-options">
                            <?php if (!empty($activities)): ?>
                                <?php foreach ($activities as $activity): ?>
                                    <li class="custom-option activity-option" data-value="<?= htmlspecialchars($activity['APP_CODE']) ?>">
                                        <div class="opt-zone">เขต: <?= htmlspecialchars($activity['szone_code']) ?> - <?= htmlspecialchars($activity['zone_name']) ?></div>
                                        <div class="opt-name"><?= htmlspecialchars($activity['APP_NAME']) ?></div>
                                        <div class="opt-dates">
                                            <b>สาขา: <?= htmlspecialchars($activity['BR_ID']) ?> : <?= htmlspecialchars($activity['BR_NAME']) ?></b><br>
                                            เดินตลาด: <span class="date-walk"><?= calculateMarketWalkDates($activity['APP_FDATE']) ?></span> | 
                                            จัด: <span class="date-event"><?= date('d/m', strtotime($activity['APP_FDATE'])) ?> - <?= date('d/m', strtotime($activity['APP_LDATE'])) ?></span>
                                        </div>
                                    </li>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <li class="custom-option" style="text-align:center; padding: 20px;">ไม่พบโครงการในขณะนี้</li>
                            <?php endif; ?>
                        </ul>
                        <select name="activity_code_select" id="activity_select" style="display:none;">
                            <option value="">-- เลือกโครงการ --</option>
                            <?php foreach ($activities as $activity): ?>
                                <option value="<?= htmlspecialchars($activity['APP_CODE']) ?>"><?= htmlspecialchars($activity['APP_NAME']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <button type="submit" class="login-btn">
                    <span>ไปที่แอป</span>
                    <i class="fas fa-arrow-right"></i>
                </button>
                
                <a href="logout.php" class="logout-secondary">ออกจากระบบ</a>
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Function to handle custom selects
            function setupCustomSelect(wrapperId, onSelect) {
                const wrapper = document.getElementById(wrapperId);
                const trigger = wrapper.querySelector('.custom-select-trigger');
                const options = wrapper.querySelectorAll('.custom-option');

                trigger.addEventListener('click', function(e) {
                    e.stopPropagation();
                    // Close other open selects
                    document.querySelectorAll('.custom-select-wrapper').forEach(w => {
                        if(w !== wrapper) w.classList.remove('open');
                    });
                    wrapper.classList.toggle('open');
                });

                options.forEach(opt => {
                    opt.addEventListener('click', function() {
                        onSelect(this);
                        wrapper.classList.remove('open');
                    });
                });
            }

            // Setup Project Select
            setupCustomSelect('wrapper-activity', function(opt) {
                const val = opt.getAttribute('data-value');
                const name = opt.querySelector('.opt-name').textContent;
                const wrapper = document.getElementById('wrapper-activity');
                wrapper.querySelector('.trigger-text').textContent = name;
                wrapper.querySelector('.trigger-text').style.fontWeight = '700';
                
                document.getElementById('activity_select').value = val;
                wrapper.querySelectorAll('.custom-option').forEach(el => el.classList.remove('selected'));
                opt.classList.add('selected');
            });

            // Setup Zone Select
            setupCustomSelect('wrapper-zone', function(opt) {
                const zone = opt.getAttribute('data-zone');
                window.location.href = 'select_activity.php?zone=' + encodeURIComponent(zone);
            });

            // Close all on window click
            document.addEventListener('click', () => {
                document.querySelectorAll('.custom-select-wrapper').forEach(w => w.classList.remove('open'));
            });

            // Auto-select activity if only one
            <?php if (count($activities) === 1): ?>
                setTimeout(() => {
                    const onlyOpt = document.querySelector('.activity-option');
                    if(onlyOpt) onlyOpt.click();
                }, 100);
            <?php endif; ?>
        });
    </script>
</body>
</html>
<?php ob_end_flush(); ?>
