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

CREATE TABLE IF NOT EXISTS admins (
 id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 username VARCHAR(100) NOT NULL UNIQUE,
 password_hash VARCHAR(255) NOT NULL,
 full_name VARCHAR(150) NOT NULL,
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS brands (
 id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 name VARCHAR(100) NOT NULL UNIQUE,
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS products (
 id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 brand_id INT UNSIGNED NOT NULL,
 display_model VARCHAR(150) NOT NULL,
 quantity INT NOT NULL DEFAULT 0,
 unit_price DECIMAL(12,2) NOT NULL DEFAULT 0,
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
 updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 CONSTRAINT fk_product_brand FOREIGN KEY (brand_id) REFERENCES brands(id)
   ON UPDATE CASCADE ON DELETE RESTRICT,
 INDEX idx_product_model(display_model)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS compatible_models (
 id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 product_id INT UNSIGNED NOT NULL,
 brand_id INT UNSIGNED NOT NULL,
 model_name VARCHAR(150) NOT NULL,
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
 CONSTRAINT fk_compat_product FOREIGN KEY (product_id) REFERENCES products(id)
   ON UPDATE CASCADE ON DELETE CASCADE,
 CONSTRAINT fk_compat_brand FOREIGN KEY (brand_id) REFERENCES brands(id)
   ON UPDATE CASCADE ON DELETE RESTRICT,
 UNIQUE KEY uq_compat(product_id,brand_id,model_name)
) ENGINE=InnoDB;

-- Correct bcrypt hash for admin123
INSERT INTO admins(username,password_hash,full_name)
VALUES('admin','$2y$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy','Administrator')
ON DUPLICATE KEY UPDATE username=username;

INSERT IGNORE INTO brands(name) VALUES
('Apple'),('Samsung'),('Xiaomi'),('Huawei'),('Oppo'),('Vivo'),('Realme'),('Nokia');
