-- =====================================================================
-- Security Guard Management & Company Assignment Dashboard
-- Database Schema (MySQL 8.0+ / MariaDB 10.5+)
-- =====================================================================
-- Design notes:
--  * All monetary values use DECIMAL, never FLOAT.
--  * Historical tables (guard_assignments, attendance, replacement_history,
--    activity_logs) are append-only from the application's point of view:
--    the API layer NEVER issues DELETE against them. "Removing" an
--    assignment sets assignment_status = 'Cancelled' instead.
--  * guards.current_company_id / current_shift are a denormalized cache
--    of "today's" assignment purely so list views don't need a join +
--    date filter on every page load. The source of truth is always
--    guard_assignments.
-- =====================================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

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

-- ---------------------------------------------------------------------
-- users : login accounts (Admin / Staff)
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS users (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    full_name       VARCHAR(120)        NOT NULL,
    username        VARCHAR(60)         NOT NULL,
    password_hash   VARCHAR(255)        NOT NULL,
    role            ENUM('admin','staff') NOT NULL DEFAULT 'staff',
    -- fine-grained permissions for staff accounts, stored as JSON, e.g.
    -- {"companies":"write","guards":"write","assignments":"write","reports":"read"}
    permissions     JSON                NULL,
    is_active       TINYINT(1)          NOT NULL DEFAULT 1,
    last_login_at   DATETIME            NULL,
    created_at      DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at      DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_users_username (username)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- companies : client companies that hire guards
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS companies (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name            VARCHAR(150)        NOT NULL,
    address         VARCHAR(255)        NOT NULL,
    contact_number  VARCHAR(30)         NOT NULL,
    alt_contact     VARCHAR(30)         NULL,
    status          ENUM('active','inactive','terminated') NOT NULL DEFAULT 'active',
    created_by      INT UNSIGNED        NULL,
    created_at      DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at      DATETIME            NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_companies_status (status),
    KEY idx_companies_name (name),
    CONSTRAINT fk_companies_created_by FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- company_agreements : the commercial contract terms for a company.
-- A company can have more than one agreement over time (renewals);
-- exactly one should be is_current = 1 at a time.
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS company_agreements (
    id                  INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    company_id          INT UNSIGNED    NOT NULL,
    guards_required     SMALLINT UNSIGNED NOT NULL,
    guard_category      ENUM('Civil','Army','Supervisor','Mixed') NOT NULL DEFAULT 'Civil',
    shift_type          ENUM('12 Hours','24 Hours') NOT NULL DEFAULT '12 Hours',
    per_guard_salary    DECIMAL(12,2)   NOT NULL,
    total_amount        DECIMAL(14,2)   NOT NULL,          -- guards_required * per_guard_salary, editable
    is_amount_overridden TINYINT(1)     NOT NULL DEFAULT 0,
    agreement_start     DATE            NOT NULL,
    agreement_end       DATE            NOT NULL,
    is_current          TINYINT(1)      NOT NULL DEFAULT 1,
    notes               TEXT            NULL,
    created_at          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_agreements_company (company_id),
    KEY idx_agreements_end (agreement_end),
    KEY idx_agreements_current (is_current),
    CONSTRAINT fk_agreements_company FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- guards : the security guards roster
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS guards (
    id                  INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name                VARCHAR(120)    NOT NULL,
    address             VARCHAR(255)    NOT NULL,
    contact_number      VARCHAR(30)     NOT NULL,
    cnic                VARCHAR(20)     NOT NULL,
    category            ENUM('Civil','Army','Supervisor') NOT NULL DEFAULT 'Civil',
    monthly_salary      DECIMAL(12,2)   NOT NULL,
    contract_start      DATE            NOT NULL,
    contract_end        DATE            NOT NULL,
    advance_amount      DECIMAL(12,2)   NOT NULL DEFAULT 0,
    remaining_amount    DECIMAL(12,2)   NOT NULL DEFAULT 0,
    status              ENUM('active','inactive','terminated','on_leave') NOT NULL DEFAULT 'active',
    -- denormalized "current" pointers, kept in sync by the assignment API
    current_company_id  INT UNSIGNED    NULL,
    current_shift        ENUM('12 Hours','24 Hours') NULL,
    photo_path          VARCHAR(255)    NULL,
    created_by          INT UNSIGNED    NULL,
    created_at          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_guards_cnic (cnic),
    KEY idx_guards_status (status),
    KEY idx_guards_category (category),
    KEY idx_guards_current_company (current_company_id),
    CONSTRAINT fk_guards_current_company FOREIGN KEY (current_company_id) REFERENCES companies(id) ON DELETE SET NULL,
    CONSTRAINT fk_guards_created_by FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- guard_references : exactly 2 rows per guard, enforced in the API layer
-- (MySQL cannot enforce "exactly N child rows" declaratively).
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS guard_references (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    guard_id        INT UNSIGNED    NOT NULL,
    ref_number      TINYINT UNSIGNED NOT NULL,   -- 1 or 2
    name            VARCHAR(120)    NOT NULL,
    address         VARCHAR(255)    NOT NULL,
    contact_number  VARCHAR(30)     NOT NULL,
    UNIQUE KEY uq_guard_ref (guard_id, ref_number),
    CONSTRAINT fk_reference_guard FOREIGN KEY (guard_id) REFERENCES guards(id) ON DELETE CASCADE,
    CONSTRAINT chk_ref_number CHECK (ref_number IN (1,2))
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- guard_contracts : optional history of contract renewals per guard
-- (mirrors company_agreements pattern; guards table holds the "current"
-- contract fields for quick reads).
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS guard_contracts (
    id              INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    guard_id        INT UNSIGNED    NOT NULL,
    monthly_salary  DECIMAL(12,2)   NOT NULL,
    contract_start  DATE            NOT NULL,
    contract_end    DATE            NOT NULL,
    advance_amount  DECIMAL(12,2)   NOT NULL DEFAULT 0,
    remaining_amount DECIMAL(12,2)  NOT NULL DEFAULT 0,
    is_current      TINYINT(1)      NOT NULL DEFAULT 1,
    created_at      DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_contracts_guard (guard_id),
    CONSTRAINT fk_contracts_guard FOREIGN KEY (guard_id) REFERENCES guards(id) ON DELETE CASCADE
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- guard_rotation_schedules : recurring rotation definitions
-- company_sequence is a JSON array of company_id values, walked in
-- order and repeated; e.g. [3,7,9] => A,B,C,A,B,C,...
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS guard_rotation_schedules (
    id                  INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    guard_id            INT UNSIGNED    NOT NULL,
    company_sequence    JSON            NOT NULL,
    shift_type          ENUM('12 Hours','24 Hours') NOT NULL DEFAULT '12 Hours',
    start_date          DATE            NOT NULL,
    end_date            DATE            NULL,
    frequency_days      SMALLINT UNSIGNED NOT NULL DEFAULT 1, -- rotate every N day(s)
    is_active           TINYINT(1)      NOT NULL DEFAULT 1,
    last_generated_date DATE            NULL,
    created_by          INT UNSIGNED    NULL,
    created_at          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_rotation_guard (guard_id),
    KEY idx_rotation_active (is_active),
    CONSTRAINT fk_rotation_guard FOREIGN KEY (guard_id) REFERENCES guards(id) ON DELETE CASCADE,
    CONSTRAINT fk_rotation_created_by FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- guard_assignments : one row = one guard, at one company, for one
-- calendar date + shift. This is the heart of the system.
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS guard_assignments (
    id                  BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    guard_id            INT UNSIGNED    NOT NULL,
    company_id          INT UNSIGNED    NOT NULL,
    assignment_date     DATE            NOT NULL,
    shift_type          ENUM('12 Hours','24 Hours') NOT NULL DEFAULT '12 Hours',
    assignment_status   ENUM('Assigned','Not Assigned','Replaced','Cancelled') NOT NULL DEFAULT 'Assigned',
    source              ENUM('manual','rotation') NOT NULL DEFAULT 'manual',
    rotation_id         INT UNSIGNED    NULL,
    notes               TEXT            NULL,
    created_by          INT UNSIGNED    NULL,
    created_at          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at          DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    -- Business rule: a guard can only have ONE active assignment per
    -- date+shift unless the administrator explicitly overrides it
    -- (override = the API inserts a new row with assignment_status
    -- appropriately reconciled; the unique key protects the default case).
    UNIQUE KEY uq_guard_date_shift (guard_id, assignment_date, shift_type),
    KEY idx_assignments_date (assignment_date),
    KEY idx_assignments_company_date (company_id, assignment_date),
    KEY idx_assignments_guard (guard_id),
    KEY idx_assignments_rotation (rotation_id),
    CONSTRAINT fk_assignment_guard FOREIGN KEY (guard_id) REFERENCES guards(id) ON DELETE CASCADE,
    CONSTRAINT fk_assignment_company FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE,
    CONSTRAINT fk_assignment_rotation FOREIGN KEY (rotation_id) REFERENCES guard_rotation_schedules(id) ON DELETE SET NULL,
    CONSTRAINT fk_assignment_created_by FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- attendance : one row per assignment. Auto-created as "Present" the
-- moment an assignment is created ("Assigned" implies "Present" by
-- default per the spec), and can be manually overridden afterwards.
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS attendance (
    id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    assignment_id   BIGINT UNSIGNED NOT NULL,
    status          ENUM('Present','Absent','Late','Leave','Replaced','Not Assigned') NOT NULL DEFAULT 'Present',
    check_in_time   TIME            NULL,
    check_out_time  TIME            NULL,
    notes           TEXT            NULL,
    marked_by       INT UNSIGNED    NULL,
    is_auto         TINYINT(1)      NOT NULL DEFAULT 1,   -- 1 = system generated, 0 = manually changed
    created_at      DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at      DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_attendance_assignment (assignment_id),
    KEY idx_attendance_status (status),
    CONSTRAINT fk_attendance_assignment FOREIGN KEY (assignment_id) REFERENCES guard_assignments(id) ON DELETE CASCADE,
    CONSTRAINT fk_attendance_marked_by FOREIGN KEY (marked_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- replacement_history : whenever a guard is swapped out mid-assignment,
-- both the original and the replacement are preserved here even though
-- the assignment row itself now points at the new guard.
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS replacement_history (
    id                      BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    assignment_id           BIGINT UNSIGNED NOT NULL,
    original_guard_id       INT UNSIGNED    NOT NULL,
    replacement_guard_id    INT UNSIGNED    NOT NULL,
    reason                  VARCHAR(255)    NULL,
    replaced_by             INT UNSIGNED    NULL,
    replaced_at             DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_replacement_assignment (assignment_id),
    KEY idx_replacement_original (original_guard_id),
    KEY idx_replacement_new (replacement_guard_id),
    CONSTRAINT fk_replacement_assignment FOREIGN KEY (assignment_id) REFERENCES guard_assignments(id) ON DELETE CASCADE,
    CONSTRAINT fk_replacement_original FOREIGN KEY (original_guard_id) REFERENCES guards(id) ON DELETE CASCADE,
    CONSTRAINT fk_replacement_new FOREIGN KEY (replacement_guard_id) REFERENCES guards(id) ON DELETE CASCADE,
    CONSTRAINT fk_replacement_by FOREIGN KEY (replaced_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- notifications : system generated + manually acknowledged alerts
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS notifications (
    id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    type            ENUM(
                        'contract_expiring_company',
                        'contract_expiring_guard',
                        'understaffed_company',
                        'missing_assignment',
                        'guard_absent',
                        'unassigned_guard',
                        'assignment_conflict'
                    ) NOT NULL,
    severity        ENUM('info','warning','critical') NOT NULL DEFAULT 'warning',
    message         VARCHAR(500)    NOT NULL,
    related_type    ENUM('company','guard','assignment') NULL,
    related_id      BIGINT UNSIGNED NULL,
    is_read         TINYINT(1)      NOT NULL DEFAULT 0,
    created_at      DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_notifications_type (type),
    KEY idx_notifications_read (is_read)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- activity_logs : audit trail for every manual change (spec rule #4:
-- "Manual changes must be recorded in history").
-- ---------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS activity_logs (
    id              BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id         INT UNSIGNED    NULL,
    action          VARCHAR(60)     NOT NULL,   -- e.g. 'assignment.create', 'attendance.override'
    entity_type     VARCHAR(40)     NOT NULL,   -- e.g. 'guard_assignments'
    entity_id       BIGINT UNSIGNED NULL,
    details         JSON            NULL,       -- free-form before/after payload
    ip_address      VARCHAR(45)     NULL,
    created_at      DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_logs_entity (entity_type, entity_id),
    KEY idx_logs_user (user_id),
    KEY idx_logs_created (created_at),
    CONSTRAINT fk_logs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB;

SET FOREIGN_KEY_CHECKS = 1;

-- ---------------------------------------------------------------------
-- Seed: one default admin account.
-- Username: admin   Password: Admin@123  (CHANGE THIS IMMEDIATELY)
-- Hash below was generated with PHP's password_hash(..., PASSWORD_DEFAULT)
-- ---------------------------------------------------------------------
INSERT INTO users (full_name, username, password_hash, role)
VALUES ('System Administrator', 'admin', '$2y$10$bNfOsTbu0aun/wbvHwJSj.ZneszUX8cQ0BUSIK2AoKq4ODwJqO2aO', 'admin')
ON DUPLICATE KEY UPDATE username = username;
