-- tkpurchase Phase 1: 협력업체 + 방문 관리 테이블

-- ① 협력업체
CREATE TABLE IF NOT EXISTS partner_companies (
  id INT AUTO_INCREMENT PRIMARY KEY,
  company_name VARCHAR(200) NOT NULL,
  business_number VARCHAR(20) UNIQUE,
  representative VARCHAR(100),
  contact_name VARCHAR(100),
  contact_phone VARCHAR(20),
  address VARCHAR(500),
  business_type JSON,
  insurance_number VARCHAR(30),
  insurance_expiry DATE,
  notes TEXT,
  is_active BOOLEAN DEFAULT TRUE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- ② 협력업체 소속 작업자
CREATE TABLE IF NOT EXISTS partner_workers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  company_id INT NOT NULL,
  worker_name VARCHAR(100) NOT NULL,
  position VARCHAR(50),
  is_team_leader BOOLEAN DEFAULT FALSE,
  phone VARCHAR(20),
  safety_training_date DATE,
  notes TEXT,
  is_active BOOLEAN DEFAULT TRUE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (company_id) REFERENCES partner_companies(id)
);

-- ③ 당일 방문 기록
CREATE TABLE IF NOT EXISTS daily_visits (
  id INT AUTO_INCREMENT PRIMARY KEY,
  visit_date DATE NOT NULL,
  company_id INT,
  company_name VARCHAR(200),
  visitor_name VARCHAR(100) NOT NULL,
  visitor_count INT DEFAULT 1,
  purpose ENUM('day_labor','equipment_repair','inspection','delivery',
               'safety_audit','client_audit','construction','other') NOT NULL,
  purpose_detail VARCHAR(500),
  workplace_name VARCHAR(200),
  safety_education_yn BOOLEAN DEFAULT FALSE,
  vehicle_number VARCHAR(20),
  check_in_time DATETIME,
  check_out_time DATETIME,
  checkout_note VARCHAR(500),
  notes TEXT,
  status ENUM('checked_in','checked_out','auto_checkout','cancelled') DEFAULT 'checked_in',
  managing_department VARCHAR(50),
  registered_by INT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_visit_date (visit_date),
  INDEX idx_company (company_id),
  INDEX idx_status (status),
  FOREIGN KEY (company_id) REFERENCES partner_companies(id) ON DELETE SET NULL
);

-- ④ 방문 건별 개별 인원 명단
CREATE TABLE IF NOT EXISTS daily_visit_workers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  daily_visit_id INT NOT NULL,
  partner_worker_id INT,
  worker_name VARCHAR(100) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (daily_visit_id) REFERENCES daily_visits(id) ON DELETE CASCADE,
  FOREIGN KEY (partner_worker_id) REFERENCES partner_workers(id) ON DELETE SET NULL
);
