CREATE DATABASE IF NOT EXISTS kempshot_sports_academy
  CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE kempshot_sports_academy;

CREATE TABLE IF NOT EXISTS ksa_roles (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    role_name VARCHAR(80) NOT NULL,
    role_slug VARCHAR(80) NOT NULL UNIQUE,
    description VARCHAR(255) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS ksa_permissions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    permission_name VARCHAR(100) NOT NULL,
    permission_slug VARCHAR(120) NOT NULL UNIQUE,
    description VARCHAR(255) NULL
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS ksa_role_permissions (
    role_id BIGINT UNSIGNED NOT NULL,
    permission_id BIGINT UNSIGNED NOT NULL,
    PRIMARY KEY (role_id, permission_id),
    CONSTRAINT fk_krp_role FOREIGN KEY (role_id) REFERENCES ksa_roles(id) ON DELETE CASCADE,
    CONSTRAINT fk_krp_permission FOREIGN KEY (permission_id) REFERENCES ksa_permissions(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS ksa_users (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    full_name VARCHAR(150) NOT NULL,
    username VARCHAR(60) NOT NULL UNIQUE,
    email VARCHAR(190) NULL UNIQUE,
    phone VARCHAR(30) NULL,
    password_hash VARCHAR(255) NOT NULL,
    status ENUM('active','inactive','suspended') NOT NULL DEFAULT 'active',
    must_change_password TINYINT(1) NOT NULL DEFAULT 1,
    last_login_at DATETIME NULL,
    last_login_ip VARCHAR(45) NULL,
    created_by BIGINT UNSIGNED NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    CONSTRAINT fk_ksa_user_creator FOREIGN KEY (created_by) REFERENCES ksa_users(id) ON DELETE SET NULL,
    INDEX idx_ksa_users_status (status)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS ksa_user_roles (
    user_id BIGINT UNSIGNED NOT NULL,
    role_id BIGINT UNSIGNED NOT NULL,
    assigned_by BIGINT UNSIGNED NULL,
    assigned_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (user_id, role_id),
    CONSTRAINT fk_kur_user FOREIGN KEY (user_id) REFERENCES ksa_users(id) ON DELETE CASCADE,
    CONSTRAINT fk_kur_role FOREIGN KEY (role_id) REFERENCES ksa_roles(id) ON DELETE RESTRICT,
    CONSTRAINT fk_kur_assigner FOREIGN KEY (assigned_by) REFERENCES ksa_users(id) ON DELETE SET NULL
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS ksa_login_attempts (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username_entered VARCHAR(190) NOT NULL,
    ip_address VARCHAR(45) NOT NULL,
    was_successful TINYINT(1) NOT NULL DEFAULT 0,
    attempted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_login_throttle (username_entered, ip_address, attempted_at)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS ksa_password_reset_tokens (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    token_hash CHAR(64) NOT NULL UNIQUE,
    expires_at DATETIME NOT NULL,
    used_at DATETIME NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_kprt_user FOREIGN KEY (user_id) REFERENCES ksa_users(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS ksa_activity_logs (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NULL,
    event_type VARCHAR(80) NOT NULL,
    event_description VARCHAR(255) NULL,
    ip_address VARCHAR(45) NULL,
    user_agent VARCHAR(255) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_kal_user FOREIGN KEY (user_id) REFERENCES ksa_users(id) ON DELETE SET NULL,
    INDEX idx_activity_user_date (user_id, created_at)
) ENGINE=InnoDB;

-- Parent accounts can later be linked to one or more player records.
-- Sponsor-to-player and scout-district scope tables should be added with
-- the Players/Scouting modules, when those entities exist.

INSERT IGNORE INTO ksa_roles (role_name, role_slug, description) VALUES
('Admin','admin','Full system administration'),
('Academy Director','academy_director','Academy oversight and approvals'),
('Coach','coach','Training, players, vitals and lineups'),
('Team Manager','team_manager','Team lists, attendance, vitals and schedules'),
('Manager','manager','Players, reports and marketing'),
('Scout','scout','Search and view players; district scouts may submit prospects'),
('Sponsor','sponsor','Payments and assigned sponsored-player visibility'),
('Parent','parent','Own child records, fees, coach chat and fixtures'),
('Staff','staff','Assigned data-entry and support functions'),
('Player','player','Own profile; read-only when enabled');

INSERT IGNORE INTO ksa_permissions (permission_name, permission_slug, description) VALUES
('Manage users','users.manage','Create, edit, suspend and assign users'),
('Manage settings','settings.manage','Manage academy system settings'),
('View all reports','reports.view_all','View all academy reports'),
('Approve schedules','schedules.approve','Approve academy schedules'),
('View variance reports','variance_reports.view','View variance reports'),
('Manage sponsors','sponsors.manage','Manage sponsor records'),
('Manage scouts','scouts.manage','Manage scout records'),
('View players','players.view','View permitted player records'),
('Create players','players.create','Create player records'),
('Edit players','players.edit','Edit academy player records'),
('Search players','players.search','Search permitted player profiles'),
('Submit prospects','prospects.submit','Submit new player prospects'),
('Verify camera sessions','training.verify_camera','Verify training sessions'),
('Manage attendance','attendance.manage','Mark and manage attendance'),
('View attendance','attendance.view','View attendance records'),
('Capture vitals','vitals.capture','Record player vitals'),
('View vitals','vitals.view','View player vitals'),
('View medical records','medical.view','View restricted medical information'),
('Upload videos','videos.upload','Upload player or training videos'),
('View videos','videos.view','View permitted videos'),
('Manage lineups','lineups.manage','Manage team lineups'),
('Manage schedules','schedules.manage','Manage team schedules'),
('View reports','reports.view','View permitted reports'),
('View marketing','marketing.view','View marketing information'),
('Manage payments','payments.manage','Manage academy payments and receipts'),
('Pay sponsor fee','sponsors.fee.pay','Pay sponsor fee and view own payment receipts'),
('View assigned sponsored players','sponsors.players.view_assigned','View only sponsored players assigned to sponsor'),
('View own child','parents.child.view_own','View only linked child records'),
('Pay school fees','parents.fees.pay','Pay fees for linked child'),
('Chat with coach','parents.coach.chat','Communicate with linked child coach'),
('View fixtures','fixtures.view','View permitted fixtures'),
('Assigned data entry','staff.data_entry.assigned','Enter data in assigned sections'),
('View assigned sections','staff.sections.view_assigned','View assigned sections'),
('View own profile','players.profile.view_own','View own player profile');

-- Role permissions reflect the supplied role sheet. Medical access is separate
-- from ordinary vitals access. Team Manager gets vitals.view, but not medical.view.
INSERT IGNORE INTO ksa_role_permissions (role_id, permission_id)
SELECT r.id, p.id FROM ksa_roles r JOIN ksa_permissions p
WHERE
(r.role_slug='admin')
OR (r.role_slug='academy_director' AND p.permission_slug IN
 ('schedules.approve','variance_reports.view','players.view','sponsors.manage','scouts.manage',
  'reports.view_all','medical.view','vitals.view','attendance.view','reports.view'))
OR (r.role_slug='coach' AND p.permission_slug IN
 ('training.verify_camera','players.view','vitals.capture','vitals.view','medical.view',
  'videos.upload','videos.view','lineups.manage','attendance.manage','attendance.view'))
OR (r.role_slug='team_manager' AND p.permission_slug IN
 ('players.view','attendance.view','vitals.view','schedules.manage'))
OR (r.role_slug='manager' AND p.permission_slug IN
 ('players.view','reports.view','marketing.view','medical.view','vitals.view'))
OR (r.role_slug='scout' AND p.permission_slug IN
 ('players.search','players.view','videos.view','prospects.submit'))
OR (r.role_slug='sponsor' AND p.permission_slug IN
 ('payments.manage','sponsors.players.view_assigned'))
OR (r.role_slug='parent' AND p.permission_slug IN
 ('parents.child.view_own','parents.fees.pay','parents.coach.chat','fixtures.view'))
OR (r.role_slug='staff' AND p.permission_slug IN
 ('staff.data_entry.assigned','staff.sections.view_assigned'))
OR (r.role_slug='player' AND p.permission_slug IN
 ('players.profile.view_own'));

-- IMPORTANT: Create the first administrator using create_admin.php after
-- importing this file. Delete create_admin.php from the web folder immediately
-- after creating the administrator.
