<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();
header('Content-Type: application/json');
$mysqli = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

// Migration: add branch_id and designation to employees if missing
function ensure_emp_migration(mysqli $db){
  $res1 = $db->query("SHOW COLUMNS FROM employees LIKE 'branch_id'");
  if (!$res1 || !$res1->fetch_assoc()) {
    @$db->query("ALTER TABLE employees ADD COLUMN branch_id INT NULL AFTER email");
    @$db->query("ALTER TABLE employees ADD CONSTRAINT fk_emp_branch FOREIGN KEY (branch_id) REFERENCES branches(id) ON DELETE SET NULL");
  }
  $res2 = $db->query("SHOW COLUMNS FROM employees LIKE 'designation'");
  if (!$res2 || !$res2->fetch_assoc()) {
    @$db->query("ALTER TABLE employees ADD COLUMN designation VARCHAR(100) NULL AFTER branch_id");
  }
  // add designation_id (FK) for master-based designation
  $res3 = $db->query("SHOW COLUMNS FROM employees LIKE 'designation_id'");
  if (!$res3 || !$res3->fetch_assoc()) {
    @$db->query("ALTER TABLE employees ADD COLUMN designation_id INT NULL AFTER designation");
    @$db->query("CREATE TABLE IF NOT EXISTS designations (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(120) NOT NULL UNIQUE, is_active TINYINT(1) NOT NULL DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB");
    @$db->query("ALTER TABLE employees ADD CONSTRAINT fk_emp_designation FOREIGN KEY (designation_id) REFERENCES designations(id) ON DELETE SET NULL");
  }
  // extra fields for ID no, address and ID copy path
  $res4 = $db->query("SHOW COLUMNS FROM employees LIKE 'id_no'");
  if (!$res4 || !$res4->fetch_assoc()) {
    @$db->query("ALTER TABLE employees ADD COLUMN id_no VARCHAR(100) NULL AFTER email");
  }
  $res5 = $db->query("SHOW COLUMNS FROM employees LIKE 'address'");
  if (!$res5 || !$res5->fetch_assoc()) {
    @$db->query("ALTER TABLE employees ADD COLUMN address TEXT NULL AFTER id_no");
  }
  $res6 = $db->query("SHOW COLUMNS FROM employees LIKE 'id_copy_path'");
  if (!$res6 || !$res6->fetch_assoc()) {
    @$db->query("ALTER TABLE employees ADD COLUMN id_copy_path VARCHAR(255) NULL AFTER address");
  }
}

function ensure_admin_emp(){ if (!has_role(['admin','super_admin'])) json_response(['message'=>'Forbidden'], 403); }

switch ($action) {
  case 'list':
    ensure_emp_migration($mysqli);
    $branch_id = isset($_GET['branch_id']) && $_GET['branch_id']!=='' ? (int)$_GET['branch_id'] : 0;
    $where = '';
    $types=''; $params=[];
    if ($branch_id) { $where = ' WHERE e.branch_id=?'; $types='i'; $params[]=$branch_id; }
    $sql = 'SELECT e.id, e.emp_code, e.full_name, e.phone, e.email, e.base_salary, e.is_active, e.branch_id, e.designation, e.designation_id, b.name AS branch_name, d.name AS designation_name FROM employees e LEFT JOIN branches b ON b.id=e.branch_id LEFT JOIN designations d ON d.id=e.designation_id' . $where . ' ORDER BY e.emp_code';
    if ($where) { $stmt=$mysqli->prepare($sql); $stmt->bind_param($types, ...$params); $stmt->execute(); $res=$stmt->get_result(); }
    else { $res = $mysqli->query($sql); }
    $data=[]; while($r=$res->fetch_assoc()){ $data[]=$r; }
    json_response(['data'=>$data]);
    break;

  case 'generate_code':
    ensure_emp_migration($mysqli);
    $next = 1;
    $res = $mysqli->query("SELECT emp_code FROM employees WHERE emp_code REGEXP '^SW[0-9]{4}$' ORDER BY emp_code DESC LIMIT 1");
    if ($res && ($row = $res->fetch_assoc())) {
      if (preg_match('/^SW(\\d{4})$/', $row['emp_code'], $m)) {
        $next = ((int)$m[1]) + 1;
      }
    }
    $code = 'SW' . str_pad((string)$next, 4, '0', STR_PAD_LEFT);
    json_response(['code' => $code]);
    break;

  case 'get':
    ensure_emp_migration($mysqli);
    $id=(int)($_GET['id'] ?? 0);
    $stmt=$mysqli->prepare('SELECT * FROM employees WHERE id=?');
    $stmt->bind_param('i',$id); $stmt->execute(); $row=$stmt->get_result()->fetch_assoc();
    json_response(['data'=>$row]);
    break;

  case 'create':
    ensure_admin_emp(); ensure_emp_migration($mysqli); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'],400);
    $emp_code=trim($_POST['emp_code'] ?? '');
    $full_name=trim($_POST['full_name'] ?? ''); if ($full_name==='') json_response(['message'=>'Full name required'],400);
    $id_no = trim($_POST['id_no'] ?? ''); if ($id_no==='') $id_no = null;
    $phone=trim($_POST['phone'] ?? '');
    $email=trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? ''); if ($address==='') $address = null;
    $branch_id = isset($_POST['branch_id']) && $_POST['branch_id']!=='' ? (int)$_POST['branch_id'] : null;
    $designation_id = isset($_POST['designation_id']) && $_POST['designation_id']!=='' ? (int)$_POST['designation_id'] : null;
    $designation = trim($_POST['designation'] ?? ''); if ($designation==='') $designation = null; // legacy text
    $base_salary=(float)($_POST['base_salary'] ?? 0);
    $is_active=(int)($_POST['is_active'] ?? 0);
    
    // Payroll fields
    $epf_no = trim($_POST['epf_no'] ?? ''); if($epf_no==='') $epf_no = null;
    $etf_no = trim($_POST['etf_no'] ?? ''); if($etf_no==='') $etf_no = null;
    $tax_no = trim($_POST['tax_no'] ?? ''); if($tax_no==='') $tax_no = null;
    
    // Bank fields
    $bank_name = trim($_POST['bank_name'] ?? ''); if($bank_name==='') $bank_name = null;
    $bank_branch = trim($_POST['bank_branch'] ?? ''); if($bank_branch==='') $bank_branch = null;
    $bank_account = trim($_POST['bank_account'] ?? ''); if($bank_account==='') $bank_account = null;
    $account_name = trim($_POST['account_name'] ?? ''); if($account_name==='') $account_name = null;
    $payment_method = in_array($_POST['payment_method'] ?? '', ['bank_transfer','cash','cheque']) ? $_POST['payment_method'] : 'bank_transfer';
    
    // Dates
    $joined_date = ($_POST['joined_date'] ?? '') !== '' ? $_POST['joined_date'] : null;
    $resigned_date = ($_POST['resigned_date'] ?? '') !== '' ? $_POST['resigned_date'] : null;
    
    // Ensure a unique employee code if missing or duplicate
    if ($emp_code === '' || ($chk = $mysqli->prepare('SELECT 1 FROM employees WHERE emp_code=? LIMIT 1')) && $chk) {
      if ($emp_code !== '') {
        $chk->bind_param('s', $emp_code);
        $chk->execute();
        $exists = $chk->get_result()->fetch_row();
      } else {
        $exists = true; // force generation
      }
      if ($exists) {
        $next = 1;
        $mx = $mysqli->query("SELECT emp_code FROM employees WHERE emp_code REGEXP '^SW[0-9]{4}$' ORDER BY emp_code DESC LIMIT 1");
        if ($mx && ($row = $mx->fetch_assoc()) && preg_match('/^SW(\\d{4})$/', $row['emp_code'], $m)) {
          $next = ((int)$m[1]) + 1;
        }
        // Loop until a free code is found (safety)
        do {
          $try = 'SW' . str_pad((string)$next, 4, '0', STR_PAD_LEFT);
          $next++;
          $stmtC = $mysqli->prepare('SELECT 1 FROM employees WHERE emp_code=? LIMIT 1');
          $stmtC->bind_param('s', $try);
          $stmtC->execute();
          $taken = $stmtC->get_result()->fetch_row();
        } while ($taken);
        $emp_code = $try;
      }
    }

    // handle file upload (optional)
    $id_copy_path = null;
    if (isset($_FILES['id_copy']) && is_uploaded_file($_FILES['id_copy']['tmp_name'])) {
      $baseDir = realpath(__DIR__ . '/../uploads'); if($baseDir===false) $baseDir = __DIR__ . '/../uploads';
      $targetDir = $baseDir . '/employee_ids'; if(!is_dir($targetDir)) @mkdir($targetDir, 0777, true);
      $ext = pathinfo($_FILES['id_copy']['name'], PATHINFO_EXTENSION);
      $safeName = 'EMP-' . preg_replace('/[^A-Za-z0-9]/','', $emp_code ?: (string)time()) . '-' . date('YmdHis') . ($ext?('.'.preg_replace('/[^a-zA-Z0-9]/','', $ext)):'');
      $targetPath = $targetDir . '/' . $safeName;
      if (!move_uploaded_file($_FILES['id_copy']['tmp_name'], $targetPath)) {
        json_response(['message'=>'Failed to upload ID copy'],500);
      }
      $id_copy_path = 'uploads/employee_ids/' . $safeName;
    }
    $stmt=$mysqli->prepare('INSERT INTO employees (emp_code, full_name, id_no, phone, email, address, branch_id, designation, designation_id, base_salary, is_active, id_copy_path, epf_no, etf_no, tax_no, bank_name, bank_branch, bank_account, account_name, payment_method, joined_date, resigned_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
    $stmt->bind_param('ssssssisidisssssssssss', $emp_code, $full_name, $id_no, $phone, $email, $address, $branch_id, $designation, $designation_id, $base_salary, $is_active, $id_copy_path, $epf_no, $etf_no, $tax_no, $bank_name, $bank_branch, $bank_account, $account_name, $payment_method, $joined_date, $resigned_date);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['message'=>'Created']);
    break;

  case 'update':
    ensure_admin_emp(); ensure_emp_migration($mysqli); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'],400);
    $id=(int)($_POST['id'] ?? 0); if(!$id) json_response(['message'=>'Missing id'],400);
    $emp_code=trim($_POST['emp_code'] ?? '');
    $full_name=trim($_POST['full_name'] ?? ''); if ($full_name==='') json_response(['message'=>'Full name required'],400);
    $id_no = trim($_POST['id_no'] ?? ''); if ($id_no==='') $id_no = null;
    $phone=trim($_POST['phone'] ?? '');
    $email=trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? ''); if ($address==='') $address = null;
    $branch_id = isset($_POST['branch_id']) && $_POST['branch_id']!=='' ? (int)$_POST['branch_id'] : null;
    $designation_id = isset($_POST['designation_id']) && $_POST['designation_id']!=='' ? (int)$_POST['designation_id'] : null;
    $designation = trim($_POST['designation'] ?? ''); if ($designation==='') $designation = null;
    $base_salary=(float)($_POST['base_salary'] ?? 0);
    $is_active=(int)($_POST['is_active'] ?? 0);
    
    // Payroll fields
    $epf_no = trim($_POST['epf_no'] ?? ''); if($epf_no==='') $epf_no = null;
    $etf_no = trim($_POST['etf_no'] ?? ''); if($etf_no==='') $etf_no = null;
    $tax_no = trim($_POST['tax_no'] ?? ''); if($tax_no==='') $tax_no = null;
    
    // Bank fields
    $bank_name = trim($_POST['bank_name'] ?? ''); if($bank_name==='') $bank_name = null;
    $bank_branch = trim($_POST['bank_branch'] ?? ''); if($bank_branch==='') $bank_branch = null;
    $bank_account = trim($_POST['bank_account'] ?? ''); if($bank_account==='') $bank_account = null;
    $account_name = trim($_POST['account_name'] ?? ''); if($account_name==='') $account_name = null;
    $payment_method = in_array($_POST['payment_method'] ?? '', ['bank_transfer','cash','cheque']) ? $_POST['payment_method'] : 'bank_transfer';
    
    // Dates
    $joined_date = ($_POST['joined_date'] ?? '') !== '' ? $_POST['joined_date'] : null;
    $resigned_date = ($_POST['resigned_date'] ?? '') !== '' ? $_POST['resigned_date'] : null;
    
    // existing file path
    $curRow = $mysqli->query('SELECT id_copy_path FROM employees WHERE id='.(int)$id.' LIMIT 1');
    $cur = $curRow && ($r=$curRow->fetch_assoc()) ? $r : null;
    $id_copy_path = $cur['id_copy_path'] ?? null;
    if (isset($_FILES['id_copy']) && is_uploaded_file($_FILES['id_copy']['tmp_name'])) {
      $baseDir = realpath(__DIR__ . '/../uploads'); if($baseDir===false) $baseDir = __DIR__ . '/../uploads';
      $targetDir = $baseDir . '/employee_ids'; if(!is_dir($targetDir)) @mkdir($targetDir, 0777, true);
      $ext = pathinfo($_FILES['id_copy']['name'], PATHINFO_EXTENSION);
      $safeName = 'EMP-' . preg_replace('/[^A-Za-z0-9]/','', $emp_code ?: (string)time()) . '-' . date('YmdHis') . ($ext?('.'.preg_replace('/[^a-zA-Z0-9]/','', $ext)):'');
      $targetPath = $targetDir . '/' . $safeName;
      if (!move_uploaded_file($_FILES['id_copy']['tmp_name'], $targetPath)) {
        json_response(['message'=>'Failed to upload ID copy'],500);
      }
      $id_copy_path = 'uploads/employee_ids/' . $safeName;
    }
    $stmt=$mysqli->prepare('UPDATE employees SET emp_code=?, full_name=?, id_no=?, phone=?, email=?, address=?, branch_id=?, designation=?, designation_id=?, base_salary=?, is_active=?, id_copy_path=?, epf_no=?, etf_no=?, tax_no=?, bank_name=?, bank_branch=?, bank_account=?, account_name=?, payment_method=?, joined_date=?, resigned_date=? WHERE id=?');
    $stmt->bind_param('ssssssisidisssssssssssi',$emp_code,$full_name,$id_no,$phone,$email,$address,$branch_id,$designation,$designation_id,$base_salary,$is_active,$id_copy_path,$epf_no,$etf_no,$tax_no,$bank_name,$bank_branch,$bank_account,$account_name,$payment_method,$joined_date,$resigned_date,$id);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['message'=>'Updated']);
    break;

  case 'delete':
    ensure_admin_emp(); if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message'=>'Invalid CSRF'],400);
    $id=(int)($_POST['id'] ?? 0); if(!$id) json_response(['message'=>'Missing id'],400);
    $stmt=$mysqli->prepare('DELETE FROM employees WHERE id=?');
    $stmt->bind_param('i',$id);
    if(!$stmt->execute()) json_response(['message'=>$stmt->error],500);
    json_response(['message'=>'Deleted']);
    break;

  default:
    json_response(['message'=>'Invalid action'],400);
}
