<?php
/**
 * api.php  –  แทน Go handlers ทั้งหมด
 * Routes (ส่งผ่าน ?action=xxx หรือ POST form action)
 *   POST  action=login
 *   GET   action=logout
 *   POST  action=save_location_rap
 *   POST  action=update_location_rap
 *   GET   action=delete_location_rap&id=xxx
 *   POST  action=save_location_rf    (multipart)
 *   POST  action=update_location_rf  (multipart)
 *   GET   action=delete_location_rf&id=xxx
 */

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth.php';   // starts session

$action = $_REQUEST['action'] ?? '';

// ─── base URL of the project (computed from script path) ───────────────────
// Compute a base path that works after deployment instead of hardcoding '/projects/kkv1'
// Force BASE to stay within the project folder (localhost setup)
define('BASE', '/advice/kkv1/ehongmd');

function redirect(string $url): void {
    header('Location: ' . $url);
    exit;
}

// ════════════════════════════════════════════════════════════════════════════
// LOGIN
// ════════════════════════════════════════════════════════════════════════════
if ($action === 'login') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        redirect(BASE . '/ehongmd/index.html');
    }

    $user = trim($_POST['USER'] ?? '');
    $pass = trim($_POST['PASS'] ?? '');

    try {
        $db  = getDB();
        $sql = "SELECT EMP_ID, US_NAME, BARCODE, US_PASSWD, TNAME, FNAME, LNAME, NICK
                FROM EHONGDB.dbo.EMPLOYEE
                WHERE EM_STATUS = 'NM'
                  AND (US_NAME = ? OR BARCODE = ?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([$user, $user]);
        $emp = $stmt->fetch();

        if (!$emp) {
            redirect(BASE . '/ehongmd/index.html?error=invalid');
        }

        $storedPass = $emp['US_PASSWD'];
        $valid      = false;

        if (str_starts_with($storedPass, '$2a$') || str_starts_with($storedPass, '$2b$') || str_starts_with($storedPass, '$2y$')) {
            // bcrypt
            $valid = password_verify($pass, $storedPass);
        } elseif (strlen($storedPass) === 32) {
            // MD5  → upgrade to bcrypt on success
                if (md5($pass) === $storedPass) {
                    $valid   = true;
                    $newHash = password_hash($pass, PASSWORD_BCRYPT);
                    try {
                        $db->prepare("UPDATE EHONGDB.dbo.EMPLOYEE SET US_PASSWD = ? WHERE EMP_ID = ?")
                           ->execute([$newHash, $emp['EMP_ID']]);
                    } catch (PDOException $e) {
                        error_log('Password upgrade skipped: ' . $e->getMessage());
                    }
                }
        } else {
            // plain text → upgrade to bcrypt on success
            if ($storedPass === $pass) {
                $valid   = true;
                $newHash = password_hash($pass, PASSWORD_BCRYPT);
                try {
                    $db->prepare("UPDATE EHONGDB.dbo.EMPLOYEE SET US_PASSWD = ? WHERE EMP_ID = ?")
                       ->execute([$newHash, $emp['EMP_ID']]);
                } catch (PDOException $e) {
                    error_log('Password upgrade skipped: ' . $e->getMessage());
                }
            }
        }

        if (!$valid) {
            redirect(BASE . '/ehongmd/index.html?error=invalid');
        }

        // สร้าง Session
        session_regenerate_id(true);
        $_SESSION['user_id']   = $emp['EMP_ID'];
        $_SESSION['user_name'] = $emp['US_NAME'];
        $_SESSION['full_name'] = trim($emp['FNAME'] . ' ' . $emp['LNAME']);

        redirect(BASE . '/ehongmd/main.php');

    } catch (PDOException $e) {
        error_log('Login DB error: ' . $e->getMessage());
        http_response_code(500);
        // Show detailed DB error for debugging (remove in production)
        echo 'Database error: ' . htmlspecialchars($e->getMessage());
    }
    exit;
}

// ════════════════════════════════════════════════════════════════════════════
// LOGOUT
// ════════════════════════════════════════════════════════════════════════════
if ($action === 'logout') {
    session_unset();
    session_destroy();
    redirect(BASE . '/ehongmd/index.html');
}

// ════════════════════════════════════════════════════════════════════════════
// ── LOCATION RAP ────────────────────────────────────────────────────────────
// ════════════════════════════════════════════════════════════════════════════

// SAVE
if ($action === 'save_location_rap') {
    requireLogin();
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE . '/ehongmd/main_1/index_2.php');
    }

    $rapName  = trim($_POST['locationName']  ?? '');
    $rapPrice = trim($_POST['rentalPrice']   ?? '0');
    $prCode   = trim($_POST['province']      ?? '');
    $rapStatus= trim($_POST['status']        ?? '');
    $rapNote  = trim($_POST['rapNote']       ?? '');

    $now      = new DateTime();
    $prefix   = 'L' . $now->format('ym');   // e.g. L2605

    try {
        $db = getDB();

        // หา RAP_IDNAME ล่าสุด
        $stmt = $db->prepare("SELECT MAX(RAP_IDNAME) FROM CONFIG.dbo.LOCATION_RAP WHERE RAP_IDNAME LIKE ?");
        $stmt->execute([$prefix . '%']);
        $maxId = $stmt->fetchColumn();

        $seq = 0;
        if ($maxId && strlen($maxId) >= 8) {
            $seq = (int) substr($maxId, 5);
        }
        $seq++;
        $newId = $prefix . str_pad($seq, 3, '0', STR_PAD_LEFT);

        // หา RAP_ID ถัดไป
        $rapId = (int) $db->query("SELECT ISNULL(MAX(RAP_ID),0) FROM CONFIG.dbo.LOCATION_RAP")->fetchColumn() + 1;

        $db->prepare("INSERT INTO CONFIG.dbo.LOCATION_RAP (RAP_ID, RAP_IDNAME, RAP_NAME, RAP_PRICE, PR_CODE, RAP_STATUS, RAP_NOTE)
                      VALUES (?, ?, ?, ?, ?, ?, ?)")
           ->execute([$rapId, $newId, $rapName, $rapPrice, $prCode, $rapStatus, $rapNote]);

        redirect(BASE . '/ehongmd/main_1/index_2.php?success=1');
    } catch (PDOException $e) {
        error_log('save_location_rap error: ' . $e->getMessage());
        http_response_code(500);
        echo 'Database error: ' . htmlspecialchars($e->getMessage());
    }
    exit;
}

// UPDATE
if ($action === 'update_location_rap') {
    requireLogin();
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE . '/ehongmd/main_1/index_2.php');
    }

    $rapId    = $_POST['rapId']       ?? '';
    $rapName  = trim($_POST['locationName']  ?? '');
    $rapPrice = trim($_POST['rentalPrice']   ?? '0');
    $prCode   = trim($_POST['province']      ?? '');
    $rapStatus= trim($_POST['status']        ?? '');
    $rapNote  = trim($_POST['rapNote']       ?? '');

    try {
        $db = getDB();
        $db->prepare("UPDATE CONFIG.dbo.LOCATION_RAP
                      SET RAP_NAME=?, RAP_PRICE=?, PR_CODE=?, RAP_STATUS=?, RAP_NOTE=?
                      WHERE RAP_ID=?")
           ->execute([$rapName, $rapPrice, $prCode, $rapStatus, $rapNote, $rapId]);

        redirect(BASE . '/ehongmd/main_1/index_2.php?success=update');
    } catch (PDOException $e) {
        error_log('update_location_rap error: ' . $e->getMessage());
        http_response_code(500);
        echo 'Database error: ' . htmlspecialchars($e->getMessage());
    }
    exit;
}

// DELETE
if ($action === 'delete_location_rap') {
    requireLogin();
    $rapId = $_GET['id'] ?? '';
    if ($rapId === '') {
        redirect(BASE . '/ehongmd/main_1/index_2.php');
    }
    try {
        $db = getDB();
        $db->prepare("DELETE FROM CONFIG.dbo.LOCATION_RAP WHERE RAP_ID=?")->execute([$rapId]);
        redirect(BASE . '/ehongmd/main_1/index_2.php?success=delete');
    } catch (PDOException $e) {
        error_log('delete_location_rap error: ' . $e->getMessage());
        http_response_code(500);
        echo 'Database error: ' . htmlspecialchars($e->getMessage());
    }
    exit;
}

// ════════════════════════════════════════════════════════════════════════════
// ── LOCATION RF ─────────────────────────────────────────────────────────────
// ════════════════════════════════════════════════════════════════════════════

function handleSlipUpload(string $rapIdName, string $rfY, string $rfM): string {
    if (!isset($_FILES['rfImg']) || $_FILES['rfImg']['error'] !== UPLOAD_ERR_OK) {
        return '';
    }
    $uploadDir = __DIR__ . '/ehongmd/images/slips/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    $ext      = strtolower(pathinfo($_FILES['rfImg']['name'], PATHINFO_EXTENSION));
    $ts       = date('YmdHis');
    $fileName = "slip_{$rapIdName}_{$rfY}_{$rfM}_{$ts}.{$ext}";
    $dest     = $uploadDir . $fileName;
    if (!move_uploaded_file($_FILES['rfImg']['tmp_name'], $dest)) {
        return '';
    }
    return $fileName;
}

// SAVE
if ($action === 'save_location_rf') {
    requireLogin();
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE . '/ehongmd/main_1/index_3.php');
    }

    $rapIdName  = trim($_POST['rapIdName']  ?? '');
    $rfM        = trim($_POST['rfM']        ?? '');
    $rfY        = trim($_POST['rfY']        ?? '');
    $payAmount  = trim($_POST['payAmount']  ?? '0');
    $rfNote     = trim($_POST['rfNote']     ?? '');

    $fileName   = handleSlipUpload($rapIdName, $rfY, $rfM);

    try {
        $db = getDB();
        $db->prepare("INSERT INTO CONFIG.dbo.LOCATION_RF (RAP_IDNAME, RF_M, RF_Y, RF_IMG, RF_PRICE, RF_NOTE)
                      VALUES (?, ?, ?, ?, ?, ?)")
           ->execute([$rapIdName, $rfM, $rfY, $fileName, $payAmount, $rfNote]);

        redirect(BASE . '/ehongmd/main_1/index_3.php?success=save');
    } catch (PDOException $e) {
        error_log('save_location_rf error: ' . $e->getMessage());
        redirect(BASE . '/ehongmd/main_1/index_3.php?error=save');
    }
    exit;
}

// UPDATE
if ($action === 'update_location_rf') {
    requireLogin();
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE . '/ehongmd/main_1/index_3.php');
    }

    $rfId      = $_POST['rfId']      ?? '';
    $rapIdName = trim($_POST['rapIdName'] ?? '');
    $rfM       = trim($_POST['rfM']       ?? '');
    $rfY       = trim($_POST['rfY']       ?? '');
    $payAmount = trim($_POST['payAmount'] ?? '0');
    $rfNoteP   = trim($_POST['rfNoteP']   ?? '');

    $fileName  = handleSlipUpload($rapIdName, $rfY, $rfM);

    try {
        $db = getDB();

        if ($fileName !== '') {
            // ลบรูปเก่า
            $old = $db->prepare("SELECT RF_IMG FROM CONFIG.dbo.LOCATION_RF WHERE RF_ID=?");
            $old->execute([$rfId]);
            $oldImg = $old->fetchColumn();
            if ($oldImg) {
                $oldPath = __DIR__ . '/ehongmd/images/slips/' . $oldImg;
                if (file_exists($oldPath)) {
                    unlink($oldPath);
                }
            }
            $db->prepare("UPDATE CONFIG.dbo.LOCATION_RF
                          SET RAP_IDNAME=?, RF_M=?, RF_Y=?, RF_IMG=?, RF_PRICE=?, RF_NOTE_P=?
                          WHERE RF_ID=?")
               ->execute([$rapIdName, $rfM, $rfY, $fileName, $payAmount, $rfNoteP, $rfId]);
        } else {
            $db->prepare("UPDATE CONFIG.dbo.LOCATION_RF
                          SET RAP_IDNAME=?, RF_M=?, RF_Y=?, RF_PRICE=?, RF_NOTE_P=?
                          WHERE RF_ID=?")
               ->execute([$rapIdName, $rfM, $rfY, $payAmount, $rfNoteP, $rfId]);
        }

        redirect(BASE . '/ehongmd/main_1/index_3.php?success=update');
    } catch (PDOException $e) {
        error_log('update_location_rf error: ' . $e->getMessage());
        redirect(BASE . '/ehongmd/main_1/index_3.php?error=update');
    }
    exit;
}

// DELETE
if ($action === 'delete_location_rf') {
    requireLogin();
    $rfId = $_GET['id'] ?? '';
    if ($rfId === '') {
        redirect(BASE . '/ehongmd/main_1/index_3.php');
    }
    try {
        $db = getDB();
        $imgRow = $db->prepare("SELECT RF_IMG FROM CONFIG.dbo.LOCATION_RF WHERE RF_ID=?");
        $imgRow->execute([$rfId]);
        $imgName = $imgRow->fetchColumn();
        if ($imgName) {
            $filePath = __DIR__ . '/ehongmd/images/slips/' . $imgName;
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }
        $db->prepare("DELETE FROM CONFIG.dbo.LOCATION_RF WHERE RF_ID=?")->execute([$rfId]);
        redirect(BASE . '/ehongmd/main_1/index_3.php?success=delete');
    } catch (PDOException $e) {
        error_log('delete_location_rf error: ' . $e->getMessage());
        redirect(BASE . '/ehongmd/main_1/index_3.php?error=delete');
    }
    exit;
}

// fallback
redirect(BASE . '/ehongmd/index.html');
