<?php
/**
 * SAS System - Professional Installer with Integrated Licensing
 * Features: License Agreement, Trial/Full License, Admin Creation, Auto-Heal, Analytics
 * Version: 4.0 - Licensed Edition
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

// ==========================================
// HTTPS ENFORCEMENT (except localhost)
// ==========================================
$is_localhost = in_array($_SERVER['SERVER_NAME'] ?? '', ['localhost', '127.0.0.1', '::1']) || 
                (isset($_SERVER['REMOTE_ADDR']) && in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']));

if (!$is_localhost && (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on')) {
    header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}

// ==========================================
// LICENSE CONFIGURATION
// ==========================================
define('LICENSE_SERVER', 'https://manage.apasaja.my/license_server.php');
define('ANALYTICS_SERVER', 'https://manage.apasaja.my/analytics_collect.php');
define('TRIAL_DAYS', 30);

// ==========================================
// LICENSE FUNCTIONS
// ==========================================

function generateTrialLicense() {
    $domain = $_SERVER['HTTP_HOST'];
    $expiresAt = date('Y-m-d H:i:s', strtotime('+' . TRIAL_DAYS . ' days'));
    
    return [
        'license_key' => 'TRIAL-' . strtoupper(substr(md5($domain . time()), 0, 16)),
        'email' => 'trial@' . $domain,
        'domain' => $domain,
        'status' => 'trial',
        'activated_at' => date('Y-m-d H:i:s'),
        'expires_at' => $expiresAt,
        'last_check' => date('Y-m-d H:i:s'),
        'fingerprint' => hash('sha256', ($_SERVER['SERVER_SOFTWARE'] ?? 'unknown') . $domain),
        'trial_started' => date('Y-m-d H:i:s'),
        'installation_id' => hash('sha256', $domain . microtime(true))
    ];
}

function activateFullLicense($licenseKey, $email) {
    $domain = $_SERVER['HTTP_HOST'];
    $fingerprint = hash('sha256', ($_SERVER['SERVER_SOFTWARE'] ?? 'unknown') . $domain);
    
    $data = [
        'action' => 'activate',
        'license_key' => $licenseKey,
        'email' => $email,
        'domain' => $domain,
        'fingerprint' => $fingerprint,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
        'software_version' => '1.0'
    ];
    
    $options = [
        'http' => [
            'header' => "Content-Type: application/json\r\n",
            'method' => 'POST',
            'content' => json_encode($data),
            'timeout' => 10
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false
        ]
    ];
    
    $context = stream_context_create($options);
    $result = @file_get_contents(LICENSE_SERVER, false, $context);
    
    if ($result === false) {
        return ['success' => false, 'message' => 'Cannot connect to license server'];
    }
    
    return json_decode($result, true) ?? ['success' => false, 'message' => 'Invalid response'];
}

function saveLicenseFile($data) {
    $json = json_encode($data);
    $key = hash('sha256', $_SERVER['HTTP_HOST'] . ($_SERVER['DOCUMENT_ROOT'] ?? __DIR__), true);
    $iv = openssl_random_pseudo_bytes(16);
    $encrypted = openssl_encrypt($json, 'AES-256-CBC', $key, 0, $iv);
    $encoded = base64_encode($iv . $encrypted);
    
    file_put_contents('license.key', $encoded);
    @chmod('license.key', 0600);
    
    return true;
}

// ==========================================

// Required PHP Extensions
$required_extensions = [
    'mysqli' => 'Database Connection',
    'pdo' => 'Database Abstraction',
    'gd' => 'Image Processing',
    'curl' => 'External APIs',
    'mbstring' => 'String Handling',
    'zip' => 'Backup & Restore',
    'json' => 'Data Handling'
];

// Required Folders
$required_folders = ['uploads', 'uploads/avatars', 'uploads/mc', 'cache', 'temp', 'backups', 'logs', 'includes'];

// Auto-Heal Folders
$folder_logs = [];
foreach ($required_folders as $dir) {
    if (!is_dir($dir)) {
        if (@mkdir($dir, 0755, true)) {
            $folder_logs[$dir] = 'Created';
        } else {
            $folder_logs[$dir] = 'Failed to create';
        }
    } else {
        // Directory already exists, check if writable
        if (is_writable($dir)) {
            $folder_logs[$dir] = 'OK';
        } else {
            // Try to fix permissions
            if (@chmod($dir, 0755)) {
                $folder_logs[$dir] = 'Fixed';
            } else {
                $folder_logs[$dir] = 'Not writable';
            }
        }
    }
}

// ==========================================
// 2. EMBEDDED SQL (Base Schema)
// ==========================================
$sql_dump = <<<'SQL'
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
SET FOREIGN_KEY_CHECKS=0;

-- TABLES
DROP TABLE IF EXISTS `announcement_hides`;
CREATE TABLE `announcement_hides` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `announcement_id` int(11) NOT NULL,
  `hidden_at` timestamp NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_hide` (`user_id`,`announcement_id`),
  KEY `announcement_id` (`announcement_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `announcement_recipients`;
CREATE TABLE `announcement_recipients` (
  `announcement_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  PRIMARY KEY (`announcement_id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `announcements`;
CREATE TABLE `announcements` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `message` text NOT NULL,
  `type` enum('global','specific') NOT NULL DEFAULT 'global',
  `target_user_id` int(11) DEFAULT NULL,
  `created_by` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `start_date` datetime DEFAULT current_timestamp(),
  `end_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `created_by` (`created_by`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `attendance_logs`;
CREATE TABLE `attendance_logs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `timetable_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `class_id` int(11) NOT NULL,
  `scan_time` datetime DEFAULT current_timestamp(),
  `latitude` decimal(10,8) DEFAULT NULL,
  `longitude` decimal(11,8) DEFAULT NULL,
  `gps_accuracy` decimal(8,2) DEFAULT NULL,
  `status` enum('present','late') DEFAULT 'present',
  `date` date GENERATED ALWAYS AS (cast(`scan_time` as date)) VIRTUAL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  KEY `scan_time` (`scan_time`),
  KEY `fk_attendance_logs_timetable` (`timetable_id`),
  KEY `idx_al_user` (`user_id`),
  KEY `idx_al_scan` (`scan_time`),
  KEY `idx_location` (`latitude`,`longitude`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `bookings`;
CREATE TABLE `bookings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `room_id` int(11) NOT NULL,
  `teacher_id` int(11) NOT NULL,
  `teacher_name` varchar(150) DEFAULT NULL,
  `booking_date` date NOT NULL,
  `start_time` time NOT NULL,
  `end_time` time NOT NULL,
  `purpose` varchar(255) NOT NULL,
  `status` enum('pending','approved','rejected') DEFAULT 'pending',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `room_id` (`room_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

DROP TABLE IF EXISTS `class_transfer_requests`;
CREATE TABLE `class_transfer_requests` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) NOT NULL,
  `from_class_id` int(11) NOT NULL,
  `to_class_id` int(11) NOT NULL,
  `requested_by` int(11) NOT NULL,
  `status` enum('pending','approved','rejected') DEFAULT 'pending',
  `reason` varchar(255) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `student_id` (`student_id`),
  KEY `from_class_id` (`from_class_id`),
  KEY `to_class_id` (`to_class_id`),
  KEY `requested_by` (`requested_by`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `class_name` varchar(50) NOT NULL,
  `qr_token` varchar(100) DEFAULT NULL,
  `class_teacher_id` int(11) DEFAULT NULL,
  `form_level` int(11) DEFAULT 0,
  `floor_level` int(1) DEFAULT 0,
  PRIMARY KEY (`id`),
  UNIQUE KEY `qr_token` (`qr_token`),
  KEY `fk_classes_class_teacher_id` (`class_teacher_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `facilities`;
CREATE TABLE `facilities` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `status` varchar(20) DEFAULT 'active',
  `icon` varchar(50) DEFAULT 'bi-box',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


DROP TABLE IF EXISTS `notifications`;
CREATE TABLE `notifications` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `message` text NOT NULL,
  `link` varchar(255) DEFAULT NULL,
  `type` varchar(50) DEFAULT NULL,
  `is_read` tinyint(1) DEFAULT 0,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

DROP TABLE IF EXISTS `public_content`;
CREATE TABLE `public_content` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` enum('news','carousel') NOT NULL,
  `title` varchar(255) DEFAULT NULL,
  `content` text DEFAULT NULL,
  `image_path` varchar(255) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;


DROP TABLE IF EXISTS `quotes`;
CREATE TABLE `quotes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` text NOT NULL,
  `author` varchar(100) DEFAULT 'Unknown',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `relief_assignments`;
CREATE TABLE `relief_assignments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `timetable_id` int(11) NOT NULL,
  `reliever_id` int(11) NOT NULL,
  `assignment_date` date NOT NULL,
  `created_by` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_relief` (`timetable_id`,`assignment_date`),
  KEY `fk_relief_assignments_reliever_id` (`reliever_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `room_facilities`;
CREATE TABLE `room_facilities` (
  `room_id` int(11) DEFAULT NULL,
  `facility_id` int(11) DEFAULT NULL,
  KEY `room_id` (`room_id`),
  KEY `facility_id` (`facility_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

DROP TABLE IF EXISTS `rooms`;
CREATE TABLE `rooms` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `capacity` int(11) DEFAULT 30,
  `location` varchar(100) DEFAULT NULL,
  `type` varchar(50) DEFAULT 'Classroom',
  `status` enum('active','maintenance') DEFAULT 'active',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

DROP TABLE IF EXISTS `school_holidays`;
CREATE TABLE `school_holidays` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(255) NOT NULL,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL,
  `type` varchar(50) NOT NULL DEFAULT 'national',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `holiday_type` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `security_logs`;
CREATE TABLE `security_logs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `event_type` varchar(50) NOT NULL,
  `username` varchar(100) DEFAULT NULL,
  `ip_address` varchar(45) NOT NULL,
  `details` text DEFAULT NULL,
  `created_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_ip_time` (`ip_address`,`created_at`),
  KEY `idx_username_time` (`username`,`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `student_attendance`;
CREATE TABLE `student_attendance` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) NOT NULL,
  `timetable_id` int(11) NOT NULL,
  `date` date NOT NULL,
  `status` enum('present','absent','late') DEFAULT 'present',
  `recorded_by` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `reason` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `student_id` (`student_id`),
  KEY `fk_student_attendance_timetable` (`timetable_id`),
  KEY `idx_sa_student` (`student_id`),
  KEY `idx_sa_date` (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `student_discipline`;
CREATE TABLE `student_discipline` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) NOT NULL,
  `timetable_id` int(11) DEFAULT NULL,
  `infraction` varchar(255) NOT NULL,
  `severity` enum('low','medium','high') DEFAULT 'low',
  `description` text DEFAULT NULL,
  `reported_by` int(11) NOT NULL,
  `reported_date` date NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `student_id` (`student_id`),
  KEY `fk_student_discipline_timetable` (`timetable_id`),
  KEY `idx_sd_student` (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

DROP TABLE IF EXISTS `student_electives`;
CREATE TABLE `student_electives` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) NOT NULL,
  `subject_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `student_id` (`student_id`,`subject_id`),
  KEY `idx_se_student` (`student_id`),
  KEY `idx_se_subject` (`subject_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

DROP TABLE IF EXISTS `students`;
CREATE TABLE `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `full_name` varchar(100) NOT NULL,
  `ic_number` varchar(12) DEFAULT NULL,
  `class_id` int(11) NOT NULL,
  `parent_phone` varchar(20) DEFAULT NULL,
  `parent_chat_id` varchar(50) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `sex` enum('Male','Female') DEFAULT NULL,
  `religion` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ic_number` (`ic_number`),
  KEY `class_id` (`class_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `subjects`;
CREATE TABLE `subjects` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `subject_name` varchar(100) NOT NULL,
  `subject_code` varchar(20) DEFAULT NULL,
  `type` enum('core','elective') DEFAULT 'core',
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_subject` (`subject_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `system_settings`;
CREATE TABLE `system_settings` (
  `setting_key` varchar(50) NOT NULL,
  `setting_value` text DEFAULT NULL,
  PRIMARY KEY (`setting_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `system_suggestions`;
CREATE TABLE `system_suggestions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `subject` varchar(255) NOT NULL,
  `message` text NOT NULL,
  `status` enum('new','read') DEFAULT 'new',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `teacher_absences`;
CREATE TABLE `teacher_absences` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `absence_date` date NOT NULL,
  `reason` varchar(255) DEFAULT NULL,
  `relief_notes` text DEFAULT NULL,
  `material_link` varchar(500) DEFAULT NULL,
  `created_by` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `attachment` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_teacher_absences_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

DROP TABLE IF EXISTS `timetable`;
CREATE TABLE `timetable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `day_of_week` int(11) NOT NULL,
  `start_time` time NOT NULL,
  `end_time` time NOT NULL,
  `class_id` int(11) NOT NULL,
  `subject` varchar(100) NOT NULL,
  `teacher_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `class_id` (`class_id`),
  KEY `day_of_week` (`day_of_week`,`start_time`,`end_time`),
  KEY `fk_timetable_teacher_id` (`teacher_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `timetable_requests`;
CREATE TABLE `timetable_requests` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `day_of_week` int(11) NOT NULL,
  `start_time` time NOT NULL,
  `end_time` time NOT NULL,
  `class_id` int(11) NOT NULL,
  `subject` varchar(100) NOT NULL,
  `teacher_id` int(11) NOT NULL,
  `status` enum('pending','approved','rejected') DEFAULT 'pending',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `request_type` enum('add','delete') DEFAULT 'add',
  `existing_timetable_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_timetable_requests_classes` (`class_id`),
  KEY `fk_timetable_requests_users` (`teacher_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `email` varchar(255) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `password` varchar(255) NOT NULL,
  `full_name` varchar(100) NOT NULL,
  `phone_number` varchar(20) DEFAULT NULL,
  `telegram_chat_id` varchar(50) DEFAULT NULL,
  `subjects` text DEFAULT NULL,
  `role` varchar(255) NOT NULL DEFAULT 'teacher',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `exclude_relief` tinyint(1) DEFAULT 0,
  `avatar` varchar(255) DEFAULT NULL,
  `max_relief_weekly` int(11) DEFAULT 3,
  `reminder_enabled` tinyint(1) DEFAULT 1,
  `reminder_minutes` int(11) DEFAULT 15,
  `reminder_sound` varchar(20) DEFAULT 'beep',
  `class_id` int(11) DEFAULT NULL,
  `layout_mode` enum('left','right') DEFAULT 'left',
  `failed_attempts` int(11) DEFAULT 0,
  `lockout_until` datetime DEFAULT NULL,
  `position_rank` int(1) DEFAULT 0,
  `is_pregnant` tinyint(1) DEFAULT 0,
  `mobility_status` enum('fit','limited_stairs','ground_floor_only') DEFAULT 'fit',
  `time_format` enum('12','24') DEFAULT '12',
  `remember_token` varchar(64) DEFAULT NULL,
  `last_login` datetime DEFAULT NULL,
  `prayer_zone` varchar(10) DEFAULT 'SGR01',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

DROP TABLE IF EXISTS `important_links`;
CREATE TABLE `important_links` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `url` varchar(255) NOT NULL,
  `category` varchar(100) DEFAULT 'Others',
  `icon` varchar(50) DEFAULT 'bi-link',
  `color` varchar(20) DEFAULT '#3b82f6',
  `target_roles` text DEFAULT '*',
  `sort_order` int(11) DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- SEED DATA
INSERT INTO `facilities` VALUES
('1','Projector','active','bi-box'),
('2','PA System','active','bi-box'),
('3','Whiteboard','active','bi-box');

INSERT INTO `quotes` VALUES
('1','The roots of education are bitter, but the fruit is sweet.','Aristotle','2025-12-09 05:05:09'),
('2','Education is the most powerful weapon which you can use to change the world.','Nelson Mandela','2025-12-09 05:05:09'),
('3','Live as if you were to die tomorrow. Learn as if you were to live forever.','Mahatma Gandhi','2025-12-09 05:05:09');

INSERT INTO `subjects` VALUES
('1','Bahasa Melayu','BM','core'),
('2','English','BI','core'),
('3','Matematik','MAT','core'),
('4','Sains','SN','core'),
('5','Sejarah','SEJ','core'),
('6','Geografi','GEO','core'),
('7','Pendidikan Islam','PI','elective'),
('8','Pendidikan Moral','PM','elective'),
('9','Pendidikan Jasmani dan Kesihatan','PJPK','core'),
('10','Pendidikan Seni Visual','PSV','elective'),
('11','Rekabentuk Teknologi','RBT','core'),
('14','Sains Komputer','SK','elective'),
('15','Asas Sains Komputer','ASK','core'),
('16','Biologi','BIO','elective'),
('17','Fizik','FZK','elective'),
('18','Kimia','KM','elective'),
('19','Matematik Tambahan','ADDM','elective'),
('20','Bahasa Arab','BA','core'),
('21','Sains Sukan','SS','elective'),
('22','Perniagaan','PN','elective'),
('23','Prinsip Perakaunan','PA','elective'),
('24','Tasawwur Islam','TI','elective');

INSERT INTO `system_settings` VALUES
('school_name','Demo School'),
('week_start_day','1'),
('start_time','07:40'),
('system_mode','live'),
('software_version','1.0.0'),
('installation_id','WILL_BE_GENERATED_ON_INSTALL');

INSERT INTO `important_links` (`title`, `description`, `url`, `category`, `icon`, `color`, `target_roles`) VALUES
('idMe (MOE Identity)', 'Single sign-on for MOE systems', 'https://idme.moe.gov.my/login', 'KPM SSO (Core)', 'bi-shield-lock-fill', '#0ea5e9', '*'),
('MOE Official Website', 'Official announcements and resources', 'https://www.moe.gov.my/', 'KPM SSO (Core)', 'bi-building', '#6366f1', '*'),
('HRMIS 2.0', 'Leave, profile, LNPT services', 'https://hrmis2.eghrmis.gov.my/', 'HR & Service', 'bi-person-badge-fill', '#f59e0b', '*'),
('eGHRMIS Portal', 'HRMIS portal + user guides', 'https://www.eghrmis.gov.my/', 'HR & Service', 'bi-journal-text', '#14b8a6', 'admin,assistant_hem,principal,assistant,akp,teacher,discipline_teacher,form6_teacher'),
('e-Operasi', 'Teacher service/placement info', 'https://eoperasi.moe.gov.my/', 'Teacher Records', 'bi-briefcase-fill', '#10b981', 'admin,assistant_hem,principal,assistant,teacher,form6_teacher,discipline_teacher'),
('e-Pangkat', 'Promotion management', 'https://epangkat.moe.gov.my/', 'Career & Movement', 'bi-award-fill', '#8b5cf6', 'admin,assistant_hem,principal,assistant,akp,teacher,form6_teacher,discipline_teacher'),
('Promotion Result', 'Online promotion result checking', 'https://naikpangkat.moe.gov.my/', 'Career & Movement', 'bi-check2-circle', '#22c55e', 'admin,assistant_hem,principal,assistant,akp,teacher,form6_teacher,discipline_teacher'),
('eGTukar', 'Transfer application', 'https://epgo.moe.gov.my/', 'Career & Movement', 'bi-arrow-left-right', '#ef4444', 'teacher,admin,assistant_hem,principal,assistant,form6_teacher,discipline_teacher'),
('DELIMa Portal', 'MOE digital learning platform', 'https://delima.moe-dl.edu.my/', 'Teaching & Learning', 'bi-laptop', '#3b82f6', '*'),
('DELIMa 2.0', 'Alternative login gateway', 'https://d2.delima.edu.my/', 'Teaching & Learning', 'bi-box-arrow-in-right', '#0ea5e9', '*'),
('SPS (School Mgmt)', 'School administration portal', 'https://public.moe.gov.my/', 'School Administration', 'bi-diagram-3-fill', '#ec4899', 'admin,assistant_hem,principal,assistant,akp');

-- CONSTRAINTS
ALTER TABLE `announcements` ADD CONSTRAINT `announcements_ibfk_1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);
ALTER TABLE `announcement_hides` ADD CONSTRAINT `announcement_hides_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
ALTER TABLE `attendance_logs` ADD CONSTRAINT `attendance_logs_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
ALTER TABLE `bookings` ADD CONSTRAINT `bookings_ibfk_1` FOREIGN KEY (`room_id`) REFERENCES `rooms` (`id`) ON DELETE CASCADE;
ALTER TABLE `classes` ADD CONSTRAINT `fk_classes_class_teacher_id` FOREIGN KEY (`class_teacher_id`) REFERENCES `users` (`id`) ON DELETE SET NULL;
ALTER TABLE `fcm_tokens` ADD CONSTRAINT `fcm_tokens_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
ALTER TABLE `relief_assignments` ADD CONSTRAINT `fk_relief_assignments_reliever_id` FOREIGN KEY (`reliever_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
ALTER TABLE `student_attendance` ADD CONSTRAINT `student_attendance_ibfk_1` FOREIGN KEY (`student_id`) REFERENCES `students` (`id`);

SET FOREIGN_KEY_CHECKS=1;
COMMIT;
SQL;


// ==========================================
// 3. CONFIG.PHP TEMPLATE (with License Integration)
// ==========================================
$new_config_code = <<<'PHP'
<?php
// Filename: config.php
if (!defined('CONFIG_LOADED')) { define('CONFIG_LOADED', true); $CONFIG_BOOTSTRAP = true; } else { $CONFIG_BOOTSTRAP = false; }
if ($CONFIG_BOOTSTRAP) {
    if (session_status() === PHP_SESSION_NONE) { session_set_cookie_params(['lifetime' => 86400, 'path' => '/', 'domain' => '', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']); session_start(); }
    require __DIR__ . '/db_connect.php';
    try { $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } catch (PDOException $e) { die("DB Error: " . $e->getMessage()); }
    date_default_timezone_set('Asia/Kuala_Lumpur');
    
      // --- [FIX] LICENSE SERVER CONFIGURATION ---
    // Menghala ke server pengurusan lesen anda
    if (!defined('LICENSE_SERVER')) {
        define('LICENSE_SERVER', 'https://manage.apasaja.my/license_server.php');
    }
    // LICENSE INTEGRATION
    require_once __DIR__ . '/sas_integration.php';
    $sas = new SASIntegration($pdo);
    $GLOBALS['sas'] = $sas;
}
$GLOBAL_SETTINGS = []; try { $stmt = $pdo->query("SELECT setting_key, setting_value FROM system_settings"); if($stmt) $GLOBAL_SETTINGS = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); } catch (Exception $e) {}
function getSetting($key, $default = '') { global $GLOBAL_SETTINGS; return $GLOBAL_SETTINGS[$key] ?? $default; }
function requireLogin() { if (!isset($_SESSION['user_id'])) { header("Location: index.php"); exit; } }
function isSchoolHoliday() { global $pdo; if (!isset($pdo)) return false; $today = date('Y-m-d'); try { $stmt = $pdo->prepare("SELECT COUNT(*) FROM school_holidays WHERE ? BETWEEN start_date AND end_date"); $stmt->execute([$today]); return $stmt->fetchColumn() > 0; } catch (Exception $e) { return false; } }
define('WONDERPUSH_MGMT_TOKEN', 'NzhmYjFkM2QwMzQ5ZTg3YTJhZmZmNTk2ZTVmZDIyMTJhY2RiYjkwN2ZjNjNjNjJmYmEzNmQ0NjYyZDcxOTA5Yw');
function sendPushNotification($userIds, $title, $message, $link = 'dashboard.php', $isDiscipline = false) {
    if (!is_array($userIds)) $userIds = [(string)$userIds]; else $userIds = array_map('strval', $userIds);
    $notification = ['alert' => ['title' => $title, 'text' => $message, 'targetUrl' => 'https://attendance.apasaja.my/' . $link]];
    if ($isDiscipline) { $notification['actions'] = [['label' => 'View Report', 'targetUrl' => 'https://attendance.apasaja.my/admin_discipline.php'], ['label' => 'Dismiss', 'action' => 'close']]; }
    $data = ['recipientUserIds' => $userIds, 'notification' => $notification];
    $ch = curl_init('https://management-api.wonderpush.com/v1/deliveries?accessToken=' . WONDERPUSH_MGMT_TOKEN);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); $result = curl_exec($ch); curl_close($ch); return $result;
}
function sendTelegram($message, $target_chat_id = null, $type = 'normal') {
    if (!in_array($type, ['otp', 'announcement', 'urgent']) && isSchoolHoliday()) return false; 
    $token = getSetting('telegram_bot_token'); $chat_id = $target_chat_id ?? getSetting('telegram_chat_id');
    if ($token && $chat_id) {
        $ch = curl_init("https://api.telegram.org/bot$token/sendMessage");
        curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['chat_id' => $chat_id, 'text' => $message, 'parse_mode' => 'HTML'])); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $res = curl_exec($ch); curl_close($ch); return $res;
    } return false;
}
function getHeaderTheme() { $mode = getSetting('header_theme', 'default'); switch ($mode) { case 'rainy': return 'linear-gradient(135deg, #475569 0%, #334155 100%)'; case 'sunny': return 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)'; case 'blue': return 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)'; case 'red': return 'linear-gradient(135deg, #dc2626 0%, #991b1b 100%)'; case 'dark': return 'linear-gradient(135deg, #1e293b 0%, #0f172a 100%)'; default: return 'linear-gradient(135deg, #8B5CF6 0%, #6366f1 100%)'; } }
?>
PHP;

// 4. REJECTION PAGE TEMPLATE
// ==========================================
$rejection_page = <<<'HTML'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>License Agreement Not Accepted</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .container {
            background: white;
            border-radius: 20px;
            padding: 50px 40px;
            max-width: 600px;
            text-align: center;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);
        }
        .icon {
            width: 100px;
            height: 100px;
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 30px;
            font-size: 3rem;
            color: white;
        }
        h1 {
            font-size: 2rem;
            color: #1e293b;
            margin-bottom: 15px;
            font-weight: 700;
        }
        p {
            color: #64748b;
            font-size: 1.1rem;
            line-height: 1.8;
            margin-bottom: 30px;
        }
        .warning-box {
            background: #fee2e2;
            border-left: 4px solid #dc2626;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            text-align: left;
        }
        .warning-box h3 {
            color: #991b1b;
            font-size: 1rem;
            margin-bottom: 10px;
        }
        .warning-box ul {
            color: #991b1b;
            margin-left: 20px;
        }
        .warning-box li {
            margin-bottom: 5px;
        }
        .footer {
            color: #94a3b8;
            font-size: 0.9rem;
            margin-top: 30px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="icon">⚠️</div>
        <h1>Installation Cancelled</h1>
        <p>You have declined the Software License Agreement. The installation cannot proceed without accepting the terms.</p>
        
        <div class="warning-box">
            <h3>📋 Required Actions:</h3>
            <ul>
                <li>Please remove all system files and source code from your server</li>
                <li>Delete the database if it was created</li>
                <li>Ensure no configuration files remain</li>
            </ul>
        </div>

        <p class="footer">
            If you wish to use this software, please restart the installation<br>
            and accept the license agreement.
        </p>
    </div>
</body>
</html>
HTML;

// ==========================================
// 5. INSTALLATION LOGIC
// ==========================================
$message = '';
$error = '';
$logs = [];
$install_success = false;
$show_completion = false;

// Handle license rejection
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reject_license') {
    file_put_contents('index.html', $rejection_page);
    header('Location: index.html');
    exit;
}

// Handle installation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'install') {
    $db_host = $_POST['db_host'] ?? 'localhost';
    $db_user = $_POST['db_user'] ?? '';
    $db_pass = $_POST['db_pass'] ?? '';
    $db_name = $_POST['db_name'] ?? '';
    
    $admin_name = strtoupper(trim($_POST['admin_name'] ?? ''));
    $admin_ic   = preg_replace('/[^0-9]/', '', $_POST['admin_ic'] ?? '');
    $admin_pass = $_POST['admin_pass'] ?? '';

    // Enhanced Validation
    if (empty($admin_name)) {
        $error = "Administrator name is required.";
    } elseif (strlen($admin_ic) !== 12) {
        $error = "IC Number must be exactly 12 digits (without dashes or spaces). You entered: " . strlen($admin_ic) . " digits.";
    } elseif (!ctype_digit($admin_ic)) {
        $error = "IC Number must contain only numbers.";
    } elseif (strlen($admin_pass) < 8) {
        $error = "Password must be at least 8 characters long.";
    } elseif (!preg_match('/[A-Z]/', $admin_pass)) {
        $error = "Password must contain at least one uppercase letter.";
    } elseif (!preg_match('/[a-z]/', $admin_pass)) {
        $error = "Password must contain at least one lowercase letter.";
    } elseif (!preg_match('/[0-9]/', $admin_pass)) {
        $error = "Password must contain at least one number.";
    } else {
        mysqli_report(MYSQLI_REPORT_OFF);
        $conn = @mysqli_connect($db_host, $db_user, $db_pass, $db_name);

        if (!$conn) {
            $error = "Database Connection Failed: " . mysqli_connect_error();
        } else {
            $logs[] = "Database connection established";
            
            if (mysqli_multi_query($conn, $sql_dump)) {
                do { if ($res = mysqli_store_result($conn)) { mysqli_free_result($res); } } while (mysqli_more_results($conn) && mysqli_next_result($conn));
                $logs[] = "Database schema created successfully";
                
                if (file_put_contents('db_connect.php', "<?php\n\$host = '$db_host';\n\$user = '$db_user';\n\$pass = '$db_pass';\n\$dbname = '$db_name';\n?>")) 
                    $logs[] = "Database configuration file generated";
                if (file_put_contents('config.php', $new_config_code)) 
                    $logs[] = "System configuration file generated";
                
                foreach ($required_folders as $dir) { 
                    if (!is_dir($dir)) mkdir($dir, 0755, true); 
                    if (is_dir($dir)) chmod($dir, 0755); 
                }
                $logs[] = "Directory structure verified and permissions set";

                $hashed_pass = password_hash($admin_pass, PASSWORD_BCRYPT);
                $stmt = mysqli_prepare($conn, "INSERT INTO users (username, full_name, password, role, created_at) VALUES (?, ?, ?, 'admin', NOW())");
                if ($stmt) {
                    mysqli_stmt_bind_param($stmt, "sss", $admin_ic, $admin_name, $hashed_pass);
                    mysqli_stmt_execute($stmt);
                    mysqli_stmt_close($stmt);
                    $logs[] = "Administrator account created (Username: $admin_ic)";
                } else {
                    $error = "Failed to create admin account: " . mysqli_error($conn);
                }

                if (!$error) {
                    $message = "Installation completed successfully!";
                    $install_success = true;
                    $show_completion = true;
                    
                    // ============================================
                    // LICENSE INTEGRATION - Handle License
                    // ============================================
                    $licenseMode = $_POST['license_mode'] ?? 'trial';
                    
                    if ($licenseMode === 'trial') {
                        // Generate trial license
                        $trialLicense = generateTrialLicense();
                        saveLicenseFile($trialLicense);
                        $logs[] = "Trial license activated (" . TRIAL_DAYS . " days)";
                    } elseif ($licenseMode === 'full') {
                        // Activate full license
                        $licenseKey = trim($_POST['license_key'] ?? '');
                        $licenseEmail = trim($_POST['license_email'] ?? '');
                        
                        if (!empty($licenseKey) && !empty($licenseEmail)) {
                            $activationResult = activateFullLicense($licenseKey, $licenseEmail);
                            
                            if ($activationResult['success']) {
                                $licenseData = [
                                    'license_key' => $licenseKey,
                                    'email' => $licenseEmail,
                                    'domain' => $_SERVER['HTTP_HOST'],
                                    'status' => 'active',
                                    'expires_at' => $activationResult['expires_at'] ?? null,
                                    'activated_at' => date('Y-m-d H:i:s'),
                                    'last_check' => date('Y-m-d H:i:s'),
                                    'fingerprint' => hash('sha256', ($_SERVER['SERVER_SOFTWARE'] ?? 'unknown') . $_SERVER['HTTP_HOST']),
                                    'installation_id' => hash('sha256', $_SERVER['HTTP_HOST'] . microtime(true))
                                ];
                                saveLicenseFile($licenseData);
                                $logs[] = "Full license activated successfully";
                            } else {
                                // Fall back to trial
                                $trialLicense = generateTrialLicense();
                                saveLicenseFile($trialLicense);
                                $logs[] = "License activation failed - Trial activated instead: " . ($activationResult['message'] ?? 'Unknown error');
                            }
                        } else {
                            // No license provided, use trial
                            $trialLicense = generateTrialLicense();
                            saveLicenseFile($trialLicense);
                            $logs[] = "Trial license activated (no full license provided)";
                        }
                    }
                    // ============================================
                    // END LICENSE INTEGRATION
                    // ============================================
                    
                    // ============================================
                    // UPDATE SYSTEM SETUP
                    // ============================================
                    $logs[] = "Configuring update system...";
                    
                    // Generate unique installation ID
                    $installationId = hash('sha256', $_SERVER['HTTP_HOST'] . microtime(true) . bin2hex(random_bytes(16)));
                    $stmt = mysqli_prepare($conn, "UPDATE system_settings SET setting_value = ? WHERE setting_key = 'installation_id'");
                    if ($stmt) {
                        mysqli_stmt_bind_param($stmt, "s", $installationId);
                        mysqli_stmt_execute($stmt);
                        mysqli_stmt_close($stmt);
                        $logs[] = "Generated unique installation ID";
                    }
                    
                    // Create update constants file
                    $constantsContent = '<?php' . "\n";
                    $constantsContent .= '/**' . "\n";
                    $constantsContent .= ' * Update System Constants' . "\n";
                    $constantsContent .= ' * Auto-generated during installation' . "\n";
                    $constantsContent .= ' */' . "\n\n";
                    $constantsContent .= 'if (!defined("UPDATE_CHECK_URL")) {' . "\n";
                    $constantsContent .= '    define("UPDATE_CHECK_URL", "https://manage.apasaja.my/update_check_api.php");' . "\n";
                    $constantsContent .= '}' . "\n\n";
                    $constantsContent .= 'if (!defined("UPDATE_DOWNLOAD_URL")) {' . "\n";
                    $constantsContent .= '    define("UPDATE_DOWNLOAD_URL", "https://manage.apasaja.my/update_download_api.php");' . "\n";
                    $constantsContent .= '}' . "\n\n";
                    $constantsContent .= 'if (!defined("UPDATE_REPORT_URL")) {' . "\n";
                    $constantsContent .= '    define("UPDATE_REPORT_URL", "https://manage.apasaja.my/update_report_api.php");' . "\n";
                    $constantsContent .= '}' . "\n";
                    
                    if (file_put_contents('includes/update_constants.php', $constantsContent)) {
                        $logs[] = "Created update configuration file";
                    }
                    
                    // Update config.php to include update constants
                    if (file_exists('config.php')) {
                        $configContent = file_get_contents('config.php');
                        if (strpos($configContent, 'update_constants.php') === false) {
                            $includeCode = "\n" . '// Update System Constants' . "\n";
                            $includeCode .= 'if (file_exists(__DIR__ . "/includes/update_constants.php")) {' . "\n";
                            $includeCode .= '    require_once __DIR__ . "/includes/update_constants.php";' . "\n";
                            $includeCode .= '}' . "\n";
                            
                            if (strpos($configContent, '?>') !== false) {
                                $configContent = str_replace('?>', $includeCode . '?>', $configContent);
                            } else {
                                $configContent .= $includeCode;
                            }
                            
                            if (file_put_contents('config.php', $configContent)) {
                                $logs[] = "Updated config.php with update system";
                            }
                        }
                    }
                    
                    $logs[] = "Update system configured successfully";
                    // ============================================
                    // END UPDATE SYSTEM SETUP
                    // ============================================
                }

            } else {
                $error = "SQL Execution Error: " . mysqli_error($conn);
            }
            mysqli_close($conn);
        }
    }
}

// Handle completion (delete installer)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'complete') {
    if (file_exists(__FILE__)) {
        @unlink(__FILE__);
        header('Location: index.php');
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SAS System - Professional Installation Wizard</title>
    <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@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    
    <style>
        :root {
            --primary: #4f46e5;
            --primary-dark: #4338ca;
            --primary-light: #6366f1;
            --secondary: #8b5cf6;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --info: #06b6d4;
            --dark: #0f172a;
            --light: #f8fafc;
            --border: #e2e8f0;
            --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
            --shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
            --shadow-lg: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
            --shadow-xl: 0 25px 50px -12px rgb(0 0 0 / 0.25);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            color: var(--dark);
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        .installer-container {
            max-width: 1100px;
            margin: 0 auto;
        }

        .installer-card {
            background: white;
            border-radius: 24px;
            box-shadow: var(--shadow-xl);
            overflow: hidden;
            animation: slideUp 0.5s ease;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .installer-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            padding: 25px 30px;
            text-align: center;
            color: white;
            position: relative;
            overflow: hidden;
        }

        .installer-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.05'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
            opacity: 0.1;
        }

        .installer-header h1 {
            font-size: 1.75rem;
            font-weight: 800;
            margin-bottom: 5px;
            position: relative;
            z-index: 1;
        }

        .installer-header .subtitle {
            font-size: 0.9rem;
            opacity: 0.95;
            font-weight: 400;
            position: relative;
            z-index: 1;
        }

        .installer-header .logo {
            width: 50px;
            height: 50px;
            background: rgba(255,255,255,0.2);
            border-radius: 12px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 12px;
            font-size: 1.5rem;
            backdrop-filter: blur(10px);
            border: 2px solid rgba(255,255,255,0.3);
        }

        .installer-body {
            padding: 25px 30px;
        }

        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 25px;
            position: relative;
        }

        .step-indicator::before {
            content: '';
            position: absolute;
            top: 16px;
            left: 0;
            right: 0;
            height: 2px;
            background: var(--border);
            z-index: 0;
        }

        .step-item {
            flex: 1;
            text-align: center;
            position: relative;
            z-index: 1;
        }

        .step-circle {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: white;
            border: 2px solid var(--border);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 0.85rem;
            margin-bottom: 6px;
            transition: all 0.3s;
        }

        .step-item.active .step-circle {
            background: var(--primary);
            border-color: var(--primary);
            color: white;
            transform: scale(1.1);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.2);
        }

        .step-item.completed .step-circle {
            background: var(--success);
            border-color: var(--success);
            color: white;
        }

        .step-label {
            font-size: 0.75rem;
            font-weight: 600;
            color: #64748b;
        }

        .step-item.active .step-label {
            color: var(--primary);
        }

        .form-section {
            background: var(--light);
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 15px;
        }

        .form-section-title {
            font-size: 1rem;
            font-weight: 700;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            color: var(--dark);
        }

        .form-section-title i {
            width: 32px;
            height: 32px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            border-radius: 8px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
        }

        .form-label {
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 6px;
            font-size: 0.85rem;
        }

        .form-control, .form-select {
            border: 2px solid var(--border);
            border-radius: 10px;
            padding: 10px 14px;
            font-size: 0.9rem;
            transition: all 0.3s;
            background: white;
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
            outline: none;
        }

        .btn {
            padding: 10px 24px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 0.9rem;
            transition: all 0.3s;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 20px -10px rgba(79, 70, 229, 0.5);
        }

        .btn-danger {
            background: linear-gradient(135deg, var(--danger) 0%, #dc2626 100%);
            color: white;
        }

        .btn-success {
            background: linear-gradient(135deg, var(--success) 0%, #059669 100%);
            color: white;
        }

        .btn-lg {
            padding: 14px 28px;
            font-size: 1rem;
        }

        .status-card {
            background: white;
            border: 2px solid var(--border);
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 12px;
            transition: all 0.3s;
        }

        .status-card:hover {
            border-color: var(--primary);
            transform: translateX(5px);
        }

        .status-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .status-card-title {
            font-weight: 700;
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #64748b;
        }

        .status-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid var(--border);
        }

        .status-item:last-child {
            border-bottom: none;
        }

        .status-name {
            font-weight: 600;
            color: var(--dark);
            font-size: 0.85rem;
        }

        .badge {
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 0.7rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .badge-success {
            background: #d1fae5;
            color: #065f46;
        }

        .badge-warning {
            background: #fef3c7;
            color: #92400e;
        }

        .badge-danger {
            background: #fee2e2;
            color: #991b1b;
        }

        .log-terminal {
            background: #1e293b;
            color: #10b981;
            padding: 15px;
            border-radius: 10px;
            font-family: 'Courier New', monospace;
            font-size: 0.8rem;
            max-height: 250px;
            overflow-y: auto;
            margin-bottom: 15px;
            box-shadow: inset 0 2px 8px rgba(0,0,0,0.3);
        }

        .log-terminal::-webkit-scrollbar {
            width: 6px;
        }

        .log-terminal::-webkit-scrollbar-track {
            background: #0f172a;
            border-radius: 3px;
        }

        .log-terminal::-webkit-scrollbar-thumb {
            background: #334155;
            border-radius: 3px;
        }

        .log-line {
            margin-bottom: 6px;
            display: flex;
            align-items: flex-start;
            gap: 8px;
        }

        .log-line i {
            margin-top: 2px;
        }

        .success-animation {
            text-align: center;
            padding: 30px 20px;
        }

        .success-icon {
            width: 70px;
            height: 70px;
            background: linear-gradient(135deg, var(--success) 0%, #059669 100%);
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 2rem;
            margin-bottom: 15px;
            animation: scaleIn 0.5s ease;
            box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
            animation: pulse 2s infinite;
        }

        @keyframes scaleIn {
            from {
                transform: scale(0);
                opacity: 0;
            }
            to {
                transform: scale(1);
                opacity: 1;
            }
        }

        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
            }
            70% {
                box-shadow: 0 0 0 20px rgba(16, 185, 129, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
            }
        }

        .alert {
            border-radius: 10px;
            padding: 12px 16px;
            border: none;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 0.9rem;
        }

        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
        }

        .alert-info {
            background: #dbeafe;
            color: #1e40af;
        }

        .alert-warning {
            background: #fef3c7;
            color: #92400e;
        }

        .code-block {
            background: #1e293b;
            color: #94a3b8;
            padding: 15px;
            border-radius: 10px;
            font-family: 'Courier New', monospace;
            font-size: 0.75rem;
            overflow-x: auto;
            margin-bottom: 15px;
            box-shadow: inset 0 2px 8px rgba(0,0,0,0.3);
            max-height: 300px;
            overflow-y: auto;
        }

        .license-box {
            background: white;
            border: 2px solid var(--border);
            border-radius: 12px;
            padding: 20px;
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
        }

        .license-box h3 {
            color: var(--primary);
            margin-bottom: 15px;
            font-size: 1.1rem;
        }

        .license-box p {
            color: var(--dark);
            line-height: 1.8;
            margin-bottom: 15px;
        }

        .license-box ul {
            margin-left: 20px;
            margin-bottom: 15px;
        }

        .license-box li {
            color: var(--dark);
            margin-bottom: 8px;
            line-height: 1.6;
        }

        .checkbox-container {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 15px;
            background: var(--light);
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .checkbox-container input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .checkbox-container label {
            font-weight: 600;
            color: var(--dark);
            cursor: pointer;
            font-size: 0.9rem;
        }

        .server-config-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .tab-btn {
            padding: 8px 16px;
            background: var(--light);
            border: 2px solid var(--border);
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.3s;
        }

        .tab-btn.active {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        @media (max-width: 768px) {
            .installer-header h1 {
                font-size: 1.5rem;
            }
            
            .installer-body {
                padding: 20px;
            }

            .step-indicator {
                flex-direction: column;
                gap: 15px;
            }

            .step-indicator::before {
                display: none;
            }

            .form-section {
                padding: 15px;
            }
        }
    </style>
</head>
<body>

<div class="installer-container">
    <div class="installer-card">
        <!-- Header -->
        <div class="installer-header">
            <div class="logo">
                <i class="bi bi-rocket-takeoff-fill"></i>
            </div>
            <h1>SAS System Installer</h1>
            <p class="subtitle">Professional Installation Wizard v3.0</p>
        </div>

        <!-- Body -->
        <div class="installer-body">

            <?php if (!$is_localhost && (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on')): ?>
                <!-- This should never show as we redirect, but just in case -->
                <div class="alert alert-danger mb-4">
                    <i class="bi bi-shield-exclamation" style="font-size: 1.5rem;"></i>
                    <div>
                        <strong>Security Warning!</strong><br>
                        This installer must run over HTTPS for security. Please access via https://
                    </div>
                </div>
            <?php elseif ($is_localhost): ?>
                <div class="alert alert-warning mb-3">
                    <i class="bi bi-laptop" style="font-size: 1.2rem;"></i>
                    <div>
                        <strong>Development Mode:</strong> Running on localhost - HTTPS not required for testing
                    </div>
                </div>
            <?php else: ?>
                <div class="alert alert-success mb-3">
                    <i class="bi bi-shield-check" style="font-size: 1.2rem;"></i>
                    <div>
                        <strong>Secure Connection:</strong> Installation running over HTTPS ✓
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($show_completion): ?>
                
                <!-- Completion Screen -->
                <div class="success-animation">
                    <div class="success-icon">
                        <i class="bi bi-check-lg"></i>
                    </div>
                    <h2 style="font-weight: 800; margin-bottom: 10px; font-size: 1.5rem;">Installation Successful!</h2>
                    <p style="color: #64748b; font-size: 0.95rem; margin-bottom: 20px;">
                        Your system has been configured and is ready to use
                    </p>

                    <div class="log-terminal">
                        <?php foreach($logs as $log): ?>
                            <div class="log-line">
                                <i class="bi bi-check2-circle"></i>
                                <span><?= htmlspecialchars($log) ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Server Configuration Recommendations -->
                    <div class="form-section" style="text-align: left;">
                        <div class="form-section-title">
                            <i class="bi bi-server"></i>
                            Server Configuration (Optional)
                        </div>

                        <div class="server-config-tabs">
                            <button class="tab-btn active" onclick="showTab('nginx')">Nginx</button>
                            <button class="tab-btn" onclick="showTab('apache')">Apache</button>
                        </div>

                        <!-- Nginx Config -->
                        <div id="nginx-tab" class="tab-content active">
                            <div class="alert alert-info mb-3">
                                <i class="bi bi-info-circle-fill"></i>
                                <div>
                                    <strong>Nginx Configuration:</strong> Copy this to your Nginx server block for optimal performance and security.
                                </div>
                            </div>
                            <div class="code-block" id="nginx-config"></div>
                        </div>

                        <!-- Apache Config -->
                        <div id="apache-tab" class="tab-content">
                            <div class="alert alert-info mb-3">
                                <i class="bi bi-info-circle-fill"></i>
                                <div>
                                    <strong>Apache Configuration:</strong> Add this to your .htaccess file.
                                </div>
                            </div>
                            <div class="code-block" id="apache-config"></div>
                        </div>
                    </div>

                    <div class="alert alert-warning mb-3">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        <div>
                            <strong>Important:</strong> Click "Complete Installation" to remove the installer file for security.
                        </div>
                    </div>

                    <form method="POST">
                        <input type="hidden" name="action" value="complete">
                        <button type="submit" class="btn btn-success btn-lg w-100">
                            <i class="bi bi-check-circle"></i>
                            Complete Installation & Remove Installer
                        </button>
                    </form>
                </div>

            <?php elseif (!isset($_POST['accept_license'])): ?>
                
                <!-- License Agreement Screen -->
                <div class="step-indicator">
                    <div class="step-item active">
                        <div class="step-circle">1</div>
                        <div class="step-label">License</div>
                    </div>
                    <div class="step-item">
                        <div class="step-circle">2</div>
                        <div class="step-label">System Check</div>
                    </div>
                    <div class="step-item">
                        <div class="step-circle">3</div>
                        <div class="step-label">Configuration</div>
                    </div>
                    <div class="step-item">
                        <div class="step-circle">4</div>
                        <div class="step-label">Complete</div>
                    </div>
                </div>

                <div class="license-box">
                    <h3>📜 Software License Agreement</h3>
                    
                    <p><strong>IMPORTANT - READ CAREFULLY:</strong></p>
                    
                    <p>This School Attendance System (SAS) is licensed software. By proceeding with the installation, you agree to the following terms:</p>

                    <h3 style="font-size: 1rem; margin-top: 20px;">Permitted Use:</h3>
                    <ul>
                        <li>This software is licensed for use by a single educational institution</li>
                        <li>You may customize the system for your institution's specific needs</li>
                        <li>You may create backups for disaster recovery purposes</li>
                    </ul>

                    <h3 style="font-size: 1rem; margin-top: 20px;">Prohibited Actions:</h3>
                    <ul>
                        <li><strong>DO NOT</strong> distribute, sell, or share this software with other institutions or individuals</li>
                        <li><strong>DO NOT</strong> remove or modify copyright notices and attribution</li>
                        <li><strong>DO NOT</strong> reverse engineer or decompile the source code</li>
                        <li><strong>DO NOT</strong> use this software for commercial purposes without explicit permission</li>
                        <li><strong>DO NOT</strong> claim this software as your own creation</li>
                    </ul>

                    <h3 style="font-size: 1rem; margin-top: 20px;">Disclaimer:</h3>
                    <ul>
                        <li>This software is provided "AS IS" without warranty of any kind</li>
                        <li>The developers are not liable for any damages arising from the use of this software</li>
                        <li>You are responsible for maintaining proper backups and security</li>
                    </ul>

                    <p style="margin-top: 20px; color: var(--danger); font-weight: 600;">
                        Violation of these terms may result in legal action and immediate termination of your license to use this software.
                    </p>
                </div>

                <div class="checkbox-container">
                    <input type="checkbox" id="agree_license" onchange="toggleAgreeButton()">
                    <label for="agree_license">I have read and agree to the Software License Agreement</label>
                </div>

                <form method="POST" id="licenseForm">
                    <div class="row g-2">
                        <div class="col-md-6">
                            <input type="hidden" name="accept_license" value="1">
                            <button type="submit" class="btn btn-primary btn-lg w-100" id="agreeBtn" disabled>
                                <i class="bi bi-check-circle"></i>
                                I Agree - Continue Installation
                            </button>
                        </div>
                        <div class="col-md-6">
                            <button type="submit" formaction="" name="action" value="reject_license" class="btn btn-danger btn-lg w-100">
                                <i class="bi bi-x-circle"></i>
                                I Do Not Agree - Exit
                            </button>
                        </div>
                    </div>
                </form>

            <?php else: ?>
                
                <!-- Installation Form -->
                <div class="step-indicator">
                    <div class="step-item completed">
                        <div class="step-circle"><i class="bi bi-check-lg"></i></div>
                        <div class="step-label">License</div>
                    </div>
                    <div class="step-item <?= $install_success ? 'completed' : 'active' ?>">
                        <div class="step-circle">
                            <?= $install_success ? '<i class="bi bi-check-lg"></i>' : '2' ?>
                        </div>
                        <div class="step-label">System Check</div>
                    </div>
                    <div class="step-item <?= $install_success ? 'completed' : '' ?>">
                        <div class="step-circle">
                            <?= $install_success ? '<i class="bi bi-check-lg"></i>' : '3' ?>
                        </div>
                        <div class="step-label">Configuration</div>
                    </div>
                    <div class="step-item <?= $install_success ? 'active' : '' ?>">
                        <div class="step-circle">4</div>
                        <div class="step-label">Complete</div>
                    </div>
                </div>

                <form method="POST" id="installForm">
                    <input type="hidden" name="action" value="install">
                    <input type="hidden" name="accept_license" value="1">
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger mb-4">
                            <i class="bi bi-exclamation-triangle-fill" style="font-size: 1.5rem;"></i>
                            <div>
                                <strong>Installation Error</strong><br>
                                <?= htmlspecialchars($error) ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- System Check Section -->
                    <div class="form-section">
                        <div class="form-section-title">
                            <i class="bi bi-shield-check"></i>
                            System Requirements Check
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <div class="status-card">
                                    <div class="status-card-header">
                                        <span class="status-card-title">PHP Extensions</span>
                                    </div>
                                    <?php foreach ($required_extensions as $ext => $desc): 
                                        $loaded = extension_loaded($ext);
                                    ?>
                                        <div class="status-item">
                                            <span class="status-name"><?= strtoupper($ext) ?></span>
                                            <span class="badge <?= $loaded ? 'badge-success' : 'badge-danger' ?>">
                                                <i class="bi bi-<?= $loaded ? 'check-circle' : 'x-circle' ?>"></i>
                                                <?= $loaded ? 'Installed' : 'Missing' ?>
                                            </span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <div class="status-card">
                                    <div class="status-card-header">
                                        <span class="status-card-title">Directory Permissions</span>
                                    </div>
                                    <?php foreach ($folder_logs as $f => $s): 
                                        $is_ok = in_array($s, ['OK', 'Created', 'Fixed']);
                                        $badge_class = $is_ok ? 'badge-success' : 'badge-danger';
                                        $icon = $is_ok ? 'check-circle' : 'x-circle';
                                        
                                        $status_text = $s;
                                        if ($s === 'OK') $status_text = 'Ready';
                                        elseif ($s === 'Created') $status_text = 'Created';
                                        elseif ($s === 'Fixed') $status_text = 'Fixed';
                                        elseif ($s === 'Not writable') $status_text = 'Error';
                                        elseif ($s === 'Failed to create') $status_text = 'Failed';
                                    ?>
                                        <div class="status-item">
                                            <span class="status-name"><?= $f ?></span>
                                            <span class="badge <?= $badge_class ?>">
                                                <i class="bi bi-<?= $icon ?>"></i>
                                                <?= $status_text ?>
                                            </span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Database Configuration -->
                    <div class="form-section">
                        <div class="form-section-title">
                            <i class="bi bi-database"></i>
                            Database Configuration
                        </div>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Database Host</label>
                                <input type="text" name="db_host" class="form-control" value="localhost" required 
                                       placeholder="localhost or IP address">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Database Name</label>
                                <input type="text" name="db_name" class="form-control" required 
                                       placeholder="Enter database name">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Database Username</label>
                                <input type="text" name="db_user" class="form-control" required 
                                       placeholder="Database user">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Database Password</label>
                                <input type="password" name="db_pass" class="form-control" 
                                       placeholder="Database password (optional)">
                            </div>
                        </div>
                    </div>

                    <!-- Administrator Setup -->
                    <div class="form-section">
                        <div class="form-section-title">
                            <i class="bi bi-person-badge"></i>

                        <!-- LICENSE ACTIVATION SECTION -->
                        <div class="form-section">
                            <div class="form-section-title">
                                <i class="bi bi-key-fill"></i>
                                License Activation
                            </div>
                            
                            <div class="alert alert-info mb-3">
                                <i class="bi bi-info-circle-fill"></i>
                                <div>
                                    <strong>Choose License Type:</strong> Start with a free 30-day trial or activate your full license now.
                                </div>
                            </div>

                            <div class="form-group">
                                <label style="display: flex; align-items: center; gap: 10px; padding: 15px; background: #f8fafc; border-radius: 8px; cursor: pointer; border: 2px solid #e2e8f0;" onclick="toggleLicenseMode('trial')">
                                    <input type="radio" name="license_mode" value="trial" id="license_trial" checked onchange="toggleLicenseMode('trial')" style="width: auto;">
                                    <div style="flex: 1;">
                                        <strong style="display: block; color: #1e293b;">🎁 Start with Trial (30 Days Free)</strong>
                                        <small style="color: #64748b;">Try all features for free. Upgrade anytime.</small>
                                    </div>
                                </label>
                            </div>

                            <div class="form-group">
                                <label style="display: flex; align-items: center; gap: 10px; padding: 15px; background: #f8fafc; border-radius: 8px; cursor: pointer; border: 2px solid #e2e8f0;" onclick="toggleLicenseMode('full')">
                                    <input type="radio" name="license_mode" value="full" id="license_full" onchange="toggleLicenseMode('full')" style="width: auto;">
                                    <div style="flex: 1;">
                                        <strong style="display: block; color: #1e293b;">🔑 Activate Full License</strong>
                                        <small style="color: #64748b;">I have a license key to activate now.</small>
                                    </div>
                                </label>
                            </div>

                            <!-- Full License Fields (hidden by default) -->
                            <div id="full_license_fields" style="display: none; margin-top: 20px; padding: 20px; background: #f1f5f9; border-radius: 10px;">
                                <div class="form-group">
                                    <label class="form-label">
                                        <i class="bi bi-key"></i> License Key
                                    </label>
                                    <input type="text" name="license_key" id="license_key" class="form-control" 
                                           placeholder="XXXX-XXXX-XXXX-XXXX" 
                                           pattern="[A-Z0-9\-]+"
                                           style="text-transform: uppercase; font-family: monospace;">
                                    <small class="text-muted">
                                        <i class="bi bi-info-circle"></i> Format: XXXX-XXXX-XXXX-XXXX
                                    </small>
                                </div>

                                <div class="form-group">
                                    <label class="form-label">
                                        <i class="bi bi-envelope"></i> License Email
                                    </label>
                                    <input type="email" name="license_email" id="license_email" class="form-control" 
                                           placeholder="your@email.com">
                                    <small class="text-muted">
                                        <i class="bi bi-envelope"></i> Email used during purchase
                                    </small>
                                </div>
                            </div>

                            <!-- Trial Info -->
                            <div id="trial_info" style="margin-top: 15px; padding: 15px; background: #dbeafe; border-left: 4px solid #3b82f6; border-radius: 8px;">
                                <strong style="color: #1e40af;">📅 Trial Period:</strong>
                                <p style="margin: 5px 0 0 0; color: #1e40af; font-size: 0.9rem;">
                                    You'll have 30 days to evaluate all features. After trial expires, you'll need to activate a full license.
                                </p>
                            </div>
                        </div>

                            Administrator Account Setup
                        </div>
                        
                        <div class="row g-3">
                            <div class="col-md-12">
                                <label class="form-label">Full Name</label>
                                <input type="text" name="admin_name" class="form-control" required 
                                       placeholder="Administrator's full name">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">IC Number (Login Username) <span class="text-danger">*</span></label>
                                <input type="text" name="admin_ic" id="admin_ic" class="form-control" required 
                                       placeholder="123456789012" 
                                       pattern="[0-9]{12}" 
                                       maxlength="12"
                                       minlength="12"
                                       oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 12)">
                                <small class="text-muted">
                                    <i class="bi bi-info-circle"></i> Exactly 12 digits, no dashes (e.g., 990101051234)
                                </small>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Password <span class="text-danger">*</span></label>
                                <input type="password" name="admin_pass" id="admin_pass" class="form-control" required 
                                       placeholder="Secure password" 
                                       minlength="8"
                                       onkeyup="checkPasswordStrength()">
                                <small class="text-muted">
                                    <i class="bi bi-shield-check"></i> Min 8 chars: uppercase, lowercase & number
                                </small>
                                <div id="password-strength" style="margin-top: 5px; font-size: 0.75rem;"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Install Button -->
                    <div class="text-center mt-4">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="bi bi-rocket-takeoff"></i>
                            Install System
                        </button>
                    </div>
                </form>

            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// License agreement checkbox
function toggleAgreeButton() {
    const checkbox = document.getElementById('agree_license');
    const btn = document.getElementById('agreeBtn');
    btn.disabled = !checkbox.checked;
}

// Password strength checker
function checkPasswordStrength() {
    const password = document.getElementById('admin_pass')?.value || '';
    const strengthDiv = document.getElementById('password-strength');
    
    if (!strengthDiv) return;
    
    let strength = 0;
    let feedback = [];
    
    // Length check
    if (password.length >= 8) {
        strength++;
    } else {
        feedback.push('8+ characters');
    }
    
    // Uppercase check
    if (/[A-Z]/.test(password)) {
        strength++;
    } else {
        feedback.push('uppercase letter');
    }
    
    // Lowercase check
    if (/[a-z]/.test(password)) {
        strength++;
    } else {
        feedback.push('lowercase letter');
    }
    
    // Number check
    if (/[0-9]/.test(password)) {
        strength++;
    } else {
        feedback.push('number');
    }
    
    // Special character bonus
    if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
        strength++;
    }
    
    // Display strength
    let color = '#ef4444';
    let text = '';
    
    if (password.length === 0) {
        strengthDiv.innerHTML = '';
        return;
    }
    
    if (strength < 3) {
        color = '#ef4444';
        text = '❌ Weak - Missing: ' + feedback.join(', ');
    } else if (strength === 3 || strength === 4) {
        color = '#f59e0b';
        text = '⚠️ Good - ' + (feedback.length ? 'Add: ' + feedback.join(', ') : 'Consider adding special characters');
    } else {
        color = '#10b981';
        text = '✅ Strong password';
    }
    
    strengthDiv.innerHTML = `<span style="color: ${color}; font-weight: 600;">${text}</span>`;
}

// IC Number real-time validation
function validateICNumber() {
    const icInput = document.getElementById('admin_ic');
    if (icInput) {
        icInput.addEventListener('input', function() {
            const value = this.value;
            const length = value.length;
            
            // Visual feedback
            if (length === 0) {
                this.style.borderColor = '';
            } else if (length === 12) {
                this.style.borderColor = '#10b981';
            } else {
                this.style.borderColor = '#f59e0b';
            }
        });
    }
}

// Initialize validators
document.addEventListener('DOMContentLoaded', function() {
    validateICNumber();
});

// Form validation feedback
document.getElementById('installForm')?.addEventListener('submit', function(e) {
    const icInput = document.getElementById('admin_ic');
    const passInput = document.getElementById('admin_pass');
    
    // Validate IC
    if (icInput && icInput.value.length !== 12) {
        e.preventDefault();
        alert('IC Number must be exactly 12 digits!');
        icInput.focus();
        return false;
    }
    
    // Validate password
    const password = passInput?.value || '';
    if (password.length < 8) {
        e.preventDefault();
        alert('Password must be at least 8 characters!');
        passInput.focus();
        return false;
    }
    
    if (!/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password)) {
        e.preventDefault();
        alert('Password must contain uppercase, lowercase, and number!');
        passInput.focus();
        return false;
    }
    
    const btn = this.querySelector('button[type="submit"]');
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> Installing...';
    btn.disabled = true;
});

// Server config tabs
function showTab(tab) {
    // Hide all tabs
    document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    
    // Show selected tab
    document.getElementById(tab + '-tab').classList.add('active');
    event.target.classList.add('active');
}

// Generate server configs
function generateServerConfigs() {
    const domain = window.location.hostname || 'yourdomain.com';
    const docRoot = '/home/attendance/public_html';
    
    const nginxConfig = `server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    
    server_name ${domain};
    root ${docRoot};
    index index.php index.html;
    
    # SSL Configuration (update paths for your SSL certificates)
    ssl_certificate /path/to/ssl.cert;
    ssl_certificate_key /path/to/ssl.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    
    # Security Headers
    add_header Cross-Origin-Resource-Policy "cross-origin" always;
    add_header Cross-Origin-Embedder-Policy "unsafe-none" always;
    add_header Cross-Origin-Opener-Policy "same-origin-allow-popups" always;
    add_header X-Frame-Options "DENY" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy "camera=(self), geolocation=(self), microphone=(self)" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
    
    # Content Security Policy
    add_header Content-Security-Policy "
        default-src 'self';
        script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com;
        style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net;
        font-src 'self' https://fonts.gstatic.com https://cdn.jsdelivr.net data:;
        img-src 'self' data: https: blob:;
        connect-src 'self' https://management-api.wonderpush.com https://api.telegram.org;
        frame-ancestors 'none';
        base-uri 'self';
        form-action 'self';
        upgrade-insecure-requests;
    " always;
    
    # Client settings
    client_max_body_size 10M;
    client_body_timeout 30s;
    client_header_timeout 30s;
    
    # Performance: Brotli & Gzip
    brotli on;
    brotli_comp_level 6;
    brotli_static on;
    brotli_types text/plain text/css application/javascript application/json image/svg+xml font/woff2;
    
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript font/woff2;
    
    # Block sensitive files
    location ~ /\\. {
        deny all;
        access_log off;
        log_not_found off;
    }
    
    location ~* \\.(sql|log|bak|backup|old|env|git|svn)$ {
        deny all;
    }
    
    location ~ ^/(config|private|db_creds|db_connect)\\.php$ {
        deny all;
    }
    
    # Static assets with long cache
    location ~* \\.(woff2|css|js)$ {
        expires 1y;
        add_header Cache-Control "public, immutable, no-transform";
        add_header Cross-Origin-Resource-Policy "cross-origin";
        access_log off;
        log_not_found off;
    }
    
    # Images
    location ~* \\.(webp|jpg|jpeg|png|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable, no-transform";
        add_header Cross-Origin-Resource-Policy "cross-origin";
        access_log off;
        log_not_found off;
    }
    
    # PHP handling (update socket path for your PHP-FPM)
    location ~ \\.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_intercept_errors on;
    }
}

# HTTP to HTTPS redirect
server {
    listen 80;
    listen [::]:80;
    server_name ${domain};
    return 301 https://${domain}$request_uri;
}`;

    const apacheConfig = `# Apache .htaccess Configuration

# Security Headers
<IfModule mod_headers.c>
    Header set X-Frame-Options "DENY"
    Header set X-Content-Type-Options "nosniff"
    Header set X-XSS-Protection "1; mode=block"
    Header set Referrer-Policy "strict-origin-when-cross-origin"
    Header set Permissions-Policy "camera=(self), geolocation=(self), microphone=(self)"
    Header set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
    Header set Cross-Origin-Resource-Policy "cross-origin"
    Header set Cross-Origin-Embedder-Policy "unsafe-none"
    Header set Cross-Origin-Opener-Policy "same-origin-allow-popups"
</IfModule>

# Compression (Brotli & Gzip)
<IfModule mod_brotli.c>
    AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/css application/javascript application/json font/woff2
</IfModule>

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/json font/woff2
</IfModule>

# Block sensitive files
<FilesMatch "\\.(sql|log|bak|backup|old|env|git|svn)$">
    Require all denied
</FilesMatch>

<FilesMatch "^(config|private|db_creds|db_connect)\\.php$">
    Require all denied
</FilesMatch>

# Cache control
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"
    ExpiresByType font/woff2 "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
</IfModule>

# URL Rewriting
<IfModule mod_rewrite.c>
    RewriteEngine On
    
    # Force HTTPS
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
    
    # Remove www
    RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
    
    # Route to index.php if file doesn't exist
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]
</IfModule>

# PHP Settings (if allowed in .htaccess)
<IfModule mod_php.c>
    php_value upload_max_filesize 10M
    php_value post_max_size 10M
    php_value max_execution_time 30
    php_value max_input_time 30
</IfModule>`;

    document.getElementById('nginx-config').textContent = nginxConfig;
    document.getElementById('apache-config').textContent = apacheConfig;
}

// Generate configs on page load if completion screen is shown
<?php if ($show_completion): ?>
    generateServerConfigs();
<?php endif; ?>
</script>


<script>
// License Mode Toggle
function toggleLicenseMode(mode) {
    const fullFields = document.getElementById('full_license_fields');
    const trialInfo = document.getElementById('trial_info');
    const trialRadio = document.getElementById('license_trial');
    const fullRadio = document.getElementById('license_full');
    
    // Get parent labels for styling
    const trialLabel = trialRadio.closest('label');
    const fullLabel = fullRadio.closest('label');
    
    if (mode === 'full') {
        fullFields.style.display = 'block';
        trialInfo.style.display = 'none';
        fullRadio.checked = true;
        
        // Update styling
        fullLabel.style.borderColor = '#4f46e5';
        fullLabel.style.background = '#eef2ff';
        trialLabel.style.borderColor = '#e2e8f0';
        trialLabel.style.background = '#f8fafc';
        
        document.getElementById('license_key').required = true;
        document.getElementById('license_email').required = true;
    } else {
        fullFields.style.display = 'none';
        trialInfo.style.display = 'block';
        trialRadio.checked = true;
        
        // Update styling
        trialLabel.style.borderColor = '#4f46e5';
        trialLabel.style.background = '#eef2ff';
        fullLabel.style.borderColor = '#e2e8f0';
        fullLabel.style.background = '#f8fafc';
        
        document.getElementById('license_key').required = false;
        document.getElementById('license_email').required = false;
    }
}

// Auto-format license key
document.addEventListener('DOMContentLoaded', function() {
    const licenseKeyInput = document.getElementById('license_key');
    if (licenseKeyInput) {
        licenseKeyInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/[^A-Z0-9]/g, '');
            let formatted = '';
            
            for (let i = 0; i < value.length && i < 16; i++) {
                if (i > 0 && i % 4 === 0) {
                    formatted += '-';
                }
                formatted += value[i];
            }
            
            e.target.value = formatted;
        });
    }
});
</script>

</body>
</html>