-- ============================================================
-- LeadYou CRM — Database Schema
-- Run this once in your MySQL database
-- ============================================================

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

-- Users table
CREATE TABLE IF NOT EXISTS users (
    id         INT AUTO_INCREMENT PRIMARY KEY,
    name       VARCHAR(100) NOT NULL,
    email      VARCHAR(150) NOT NULL UNIQUE,
    password   VARCHAR(255) NOT NULL,       -- bcrypt hashed
    role       ENUM('admin','user') DEFAULT 'user',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Leads table
CREATE TABLE IF NOT EXISTS leads (
    id         INT AUTO_INCREMENT PRIMARY KEY,
    name       VARCHAR(100) NOT NULL,
    email      VARCHAR(150) NOT NULL,
    phone      VARCHAR(30),
    company    VARCHAR(100),
    status     ENUM('New','Contacted','Qualified','Proposal','Won','Lost') DEFAULT 'New',
    notes      TEXT,
    created_by INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
);

-- Seed an admin user (password: admin123 — change immediately!)
INSERT INTO users (name, email, password, role) VALUES
('Admin', 'admin@leadyou.com', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'admin');

-- Indexes for performance
CREATE INDEX idx_leads_status     ON leads(status);
CREATE INDEX idx_leads_created_at ON leads(created_at);
CREATE INDEX idx_leads_email      ON leads(email);
