-- =========================================================
-- Digital Signage System - Database Schema
-- Engine: MySQL 5.7+ / MariaDB 10.3+ (utf8mb4 for Arabic support)
-- =========================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ---------------------------------------------------------
-- 1. Branches (الفروع)
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS branches (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(150) NOT NULL,
    name_en VARCHAR(150) DEFAULT NULL,
    city VARCHAR(100) DEFAULT NULL,
    address VARCHAR(255) DEFAULT NULL,
    is_self_managed TINYINT(1) NOT NULL DEFAULT 0 COMMENT '0=centrally managed by super admin, 1=branch manages itself',
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------
-- 2. Users (المستخدمون - Super Admin / Branch Admin)
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    branch_id INT UNSIGNED DEFAULT NULL COMMENT 'NULL for super_admin',
    full_name VARCHAR(150) NOT NULL,
    username VARCHAR(60) NOT NULL UNIQUE,
    email VARCHAR(150) DEFAULT NULL,
    password_hash VARCHAR(255) NOT NULL,
    role ENUM('super_admin','branch_admin') NOT NULL DEFAULT 'branch_admin',
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    last_login DATETIME DEFAULT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    CONSTRAINT fk_users_branch FOREIGN KEY (branch_id) REFERENCES branches(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------
-- 3. Screens (الشاشات) - each screen has a unique access token
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS screens (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    branch_id INT UNSIGNED NOT NULL,
    name VARCHAR(150) NOT NULL COMMENT 'e.g. شاشة الاستقبال',
    screen_token VARCHAR(64) NOT NULL UNIQUE COMMENT 'used in player URL, unguessable',
    screen_code CHAR(6) DEFAULT NULL COMMENT 'human-typed 6-digit pairing code shown once on the display device',
    orientation ENUM('landscape','portrait') NOT NULL DEFAULT 'landscape',
    resolution VARCHAR(20) DEFAULT NULL COMMENT 'e.g. 1920x1080',
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    last_ping DATETIME DEFAULT NULL COMMENT 'last time player checked in - for online/offline status',
    last_ip VARCHAR(45) DEFAULT NULL,
    playlist_id INT UNSIGNED DEFAULT NULL COMMENT 'directly assigned playlist (overridden by day-part schedule if present)',
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    CONSTRAINT fk_screens_branch FOREIGN KEY (branch_id) REFERENCES branches(id) ON DELETE CASCADE,
    INDEX idx_screen_token (screen_token),
    UNIQUE KEY uniq_screen_code (screen_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------
-- 4. Media Library (مكتبة الوسائط) - images/videos
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS media (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    branch_id INT UNSIGNED DEFAULT NULL COMMENT 'NULL = shared/global media usable by all branches',
    type ENUM('image','video') NOT NULL,
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(500) NOT NULL,
    file_size INT UNSIGNED DEFAULT NULL COMMENT 'bytes',
    mime_type VARCHAR(100) DEFAULT NULL,
    width INT UNSIGNED DEFAULT NULL,
    height INT UNSIGNED DEFAULT NULL,
    duration_seconds INT UNSIGNED DEFAULT NULL COMMENT 'for videos',
    uploaded_by INT UNSIGNED DEFAULT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_media_branch FOREIGN KEY (branch_id) REFERENCES branches(id) ON DELETE CASCADE,
    CONSTRAINT fk_media_user FOREIGN KEY (uploaded_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------
-- 5. Menu Categories (تصنيفات المنيو) - e.g. فطار / غدا / عشا / مشروبات
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS menu_categories (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    branch_id INT UNSIGNED DEFAULT NULL COMMENT 'NULL = shared category template',
    name VARCHAR(150) NOT NULL,
    sort_order INT NOT NULL DEFAULT 0,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_menucat_branch FOREIGN KEY (branch_id) REFERENCES branches(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------
-- 6. Menu Items (أصناف المنيو)
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS menu_items (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    branch_id INT UNSIGNED NOT NULL,
    category_id INT UNSIGNED DEFAULT NULL,
    name VARCHAR(200) NOT NULL,
    description VARCHAR(500) DEFAULT NULL,
    price DECIMAL(10,2) DEFAULT NULL,
    price_after_discount DECIMAL(10,2) DEFAULT NULL,
    image_media_id INT UNSIGNED DEFAULT NULL,
    is_available TINYINT(1) NOT NULL DEFAULT 1,
    sort_order INT NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    CONSTRAINT fk_menuitem_branch FOREIGN KEY (branch_id) REFERENCES branches(id) ON DELETE CASCADE,
    CONSTRAINT fk_menuitem_cat FOREIGN KEY (category_id) REFERENCES menu_categories(id) ON DELETE SET NULL,
    CONSTRAINT fk_menuitem_media FOREIGN KEY (image_media_id) REFERENCES media(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------
-- 7. Playlists (قوائم التشغيل) - ordered sequence of slides
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS playlists (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    branch_id INT UNSIGNED DEFAULT NULL COMMENT 'NULL = global playlist manageable by super admin only',
    name VARCHAR(150) NOT NULL,
    day_part ENUM('none','breakfast','lunch','dinner') NOT NULL DEFAULT 'none' COMMENT 'used by scheduler to auto-pick playlist by time of day',
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    CONSTRAINT fk_playlist_branch FOREIGN KEY (branch_id) REFERENCES branches(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------
-- 8. Playlist Items (عناصر قائمة التشغيل) - polymorphic slide content
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS playlist_items (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    playlist_id INT UNSIGNED NOT NULL,
    item_type ENUM('media','menu_category','html') NOT NULL DEFAULT 'media',
    media_id INT UNSIGNED DEFAULT NULL,
    menu_category_id INT UNSIGNED DEFAULT NULL,
    html_content TEXT DEFAULT NULL COMMENT 'for custom text/announcement slides',
    duration_seconds INT UNSIGNED NOT NULL DEFAULT 10,
    sort_order INT NOT NULL DEFAULT 0,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_playlistitem_playlist FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
    CONSTRAINT fk_playlistitem_media FOREIGN KEY (media_id) REFERENCES media(id) ON DELETE CASCADE,
    CONSTRAINT fk_playlistitem_cat FOREIGN KEY (menu_category_id) REFERENCES menu_categories(id) ON DELETE CASCADE,
    INDEX idx_playlist_sort (playlist_id, sort_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------
-- 9. Day-part Schedules (جدولة الفترات الزمنية) per branch
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS day_part_schedules (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    branch_id INT UNSIGNED NOT NULL,
    day_part ENUM('breakfast','lunch','dinner') NOT NULL,
    start_time TIME NOT NULL,
    end_time TIME NOT NULL,
    playlist_id INT UNSIGNED DEFAULT NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    CONSTRAINT fk_daypart_branch FOREIGN KEY (branch_id) REFERENCES branches(id) ON DELETE CASCADE,
    CONSTRAINT fk_daypart_playlist FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE SET NULL,
    UNIQUE KEY uniq_branch_daypart (branch_id, day_part)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------
-- 10. System Settings (إعدادات النظام العامة)
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS settings (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    setting_key VARCHAR(100) NOT NULL UNIQUE,
    setting_value TEXT DEFAULT NULL,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------
-- 11. Activity Log (سجل النشاط) - audit trail
-- ---------------------------------------------------------
CREATE TABLE IF NOT EXISTS activity_log (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id INT UNSIGNED DEFAULT NULL,
    branch_id INT UNSIGNED DEFAULT NULL,
    action VARCHAR(255) NOT NULL,
    details TEXT DEFAULT NULL,
    ip_address VARCHAR(45) DEFAULT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_log_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL,
    CONSTRAINT fk_log_branch FOREIGN KEY (branch_id) REFERENCES branches(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

SET FOREIGN_KEY_CHECKS = 1;

-- =========================================================
-- Seed Data
-- =========================================================

-- Default super admin (username: admin / password: Admin@12345)
-- Password hash generated with PHP password_hash() - bcrypt - VERIFIED working with password_verify()
-- IMPORTANT: change this password immediately after first login via the Users page.
INSERT INTO users (branch_id, full_name, username, email, password_hash, role, is_active)
VALUES (NULL, 'مدير النظام', 'admin', 'admin@example.com', '$2y$10$17yEv.XMslyYlArsB1AzmeCoaKZne11lMLkx.ReAdEAg1kjG.JzGu', 'super_admin', 1);

-- 5 Branches
INSERT INTO branches (name, name_en, city, is_self_managed, is_active) VALUES
('فرع أبها الرئيسي', 'Abha Main Branch', 'أبها', 0, 1),
('فرع خميس مشيط', 'Khamis Mushait Branch', 'خميس مشيط', 0, 1),
('فرع النماص', 'Al Namas Branch', 'النماص', 0, 1),
('فرع بيشة', 'Bisha Branch', 'بيشة', 0, 1),
('فرع جازان', 'Jazan Branch', 'جازان', 0, 1);

-- Default global settings
INSERT INTO settings (setting_key, setting_value) VALUES
('site_name', 'نظام العرض الرقمي - NEOTRISH'),
('default_slide_duration', '10'),
('player_poll_interval', '15'),
('offline_threshold_seconds', '60');
