<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");

// กำหนดค่าการเชื่อมต่อ MySQL (แก้ไขให้ตรงกับเซิร์ฟเวอร์ของคุณ)
$host = "localhost";
$username = "root";
$password = "";
$dbname = "employee_db";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    echo json_encode(["success" => false, "message" => "Database connection failed"]);
    exit;
}

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

switch ($action) {
    case 'getEmployees':
        try {
            $stmt = $pdo->query("SELECT emp_id, name, dept, division, pos, img, phone, is_fav FROM employees ORDER BY name ASC");
            $employees = $stmt->fetchAll();
            foreach ($employees as &$emp) {
                $emp['is_fav'] = (bool)$emp['is_fav'];
            }
            echo json_encode($employees);
        } catch (Exception $e) {
            echo json_encode([]);
        }
        break;

    case 'addOrUpdateEmployee':
        // ดึงข้อมูลและตัดช่องว่าง ค้นหาผ่าน $_POST และ $_REQUEST ป้องกัน Strict Mode
        $empId = isset($_POST['empId']) ? trim($_POST['empId']) : '';
        $name = isset($_POST['name']) ? trim($_POST['name']) : '';
        
        if (empty($empId)) { $empId = isset($_REQUEST['empId']) ? trim($_REQUEST['empId']) : ''; }
        if (empty($name)) { $name = isset($_REQUEST['name']) ? trim($_REQUEST['name']) : ''; }

        if ($empId === '' || $name === '') {
            echo json_encode(["success" => false, "message" => "ข้อมูลไม่ครบถ้วน (กรุณาระบุ ID และ ชื่อพนักงาน)"]);
            break;
        }

        $dept = $_POST['dept'] ?? '';
        $div = $_POST['div'] ?? '';
        $pos = $_POST['pos'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $isFav = ($_POST['isFav'] === 'true' || $_POST['isFav'] === '1' || $_POST['isFav'] === true) ? 1 : 0;
        
        $imgName = $_POST['currentImg'] ?? '';

        // บริหารจัดการไฟล์อัปโหลดรูปภาพ
        if (!empty($_FILES['imgFile']['name'])) {
            $file = $_FILES['imgFile'];
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

            if (in_array($ext, $allowed)) {
                $cleanEmpId = preg_replace('/[^A-Za-z0-9_\-]/', '', $empId);
                $imgName = $cleanEmpId . "_" . time() . "." . $ext;
                $target = "uploads/" . $imgName;

                if (!is_dir('uploads')) {
                    @mkdir('uploads', 0777, true);
                }

                if (move_uploaded_file($file['tmp_name'], $target)) {
                    if (!empty($_POST['currentImg']) && file_exists("uploads/" . $_POST['currentImg'])) {
                        @unlink("uploads/" . $_POST['currentImg']);
                    }
                } else {
                    echo json_encode(["success" => false, "message" => "ไม่สามารถย้ายไฟล์ลงโฟลเดอร์ uploads ได้ ตรวจสอบสิทธิ์สิทธิ์เขียนโฟลเดอร์"]);
                    break;
                }
            } else {
                echo json_encode(["success" => false, "message" => "ระบบรองรับเฉพาะไฟล์รูปภาพหลักเท่านั้น"]);
                break;
            }
        }

        try {
            $sql = "INSERT INTO employees (emp_id, name, dept, division, pos, img, phone, is_fav) 
                    VALUES (:emp_id, :name, :dept, :division, :pos, :img, :phone, :is_fav)
                    ON DUPLICATE KEY UPDATE 
                        name = :name2, dept = :dept2, division = :division2, 
                        pos = :pos2, img = :img2, phone = :phone2, is_fav = :is_fav2";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':emp_id' => $empId, ':name' => $name, ':dept' => $dept, ':division' => $div, ':pos' => $pos, ':img' => $imgName, ':phone' => $phone, ':is_fav' => $isFav,
                ':name2' => $name, ':dept2' => $dept, ':division2' => $div, ':pos2' => $pos, ':img2' => $imgName, ':phone2' => $phone, ':is_fav2' => $isFav
            ]);

            echo json_encode(["success" => true]);
        } catch (Exception $e) {
            echo json_encode(["success" => false, "message" => "Database Error: " . $e->getMessage()]);
        }
        break;

    case 'toggleFavorite':
        $input = json_decode(file_get_contents("php://input"), true);
        if (!$input || empty($input['empId'])) { echo json_encode(["success" => false]); break; }
        try {
            $stmt = $pdo->prepare("UPDATE employees SET is_fav = :is_fav WHERE emp_id = :emp_id");
            $stmt->execute([':is_fav' => $input['isFav'] ? 1 : 0, ':emp_id' => $input['empId']]);
            echo json_encode(["success" => true]);
        } catch (Exception $e) { echo json_encode(["success" => false]); }
        break;

    case 'deleteEmployee':
        $input = json_decode(file_get_contents("php://input"), true);
        if (!$input || empty($input['empId'])) { echo json_encode(["success" => false]); break; }
        try {
            $stmtImg = $pdo->prepare("SELECT img FROM employees WHERE emp_id = :emp_id");
            $stmtImg->execute([':emp_id' => $input['empId']]);
            $emp = $stmtImg->fetch();
            if (!empty($emp['img']) && file_exists("uploads/" . $emp['img'])) {
                @unlink("uploads/" . $emp['img']);
            }

            $stmt = $pdo->prepare("DELETE FROM employees WHERE emp_id = :emp_id");
            $stmt->execute([':emp_id' => $input['empId']]);
            echo json_encode(["success" => true]);
        } catch (Exception $e) { echo json_encode(["success" => false]); }
        break;

    default:
        echo json_encode(["success" => false, "message" => "Unknown Action"]);
        break;
}