<?php
class Employee_model {
    private $db;
    public function __construct() {
        $this->db = new Database;
    }

    public function getAllEmployees() {
        $res = $this->db->query("SELECT * FROM employees ORDER BY id DESC");
        return $res ? mysqli_fetch_all($res, MYSQLI_ASSOC) : [];
    }

    public function insertEmployee($data, $files = []) {
        $name = $this->db->escape($data['name'] ?? '');
        $position = $this->db->escape($data['position'] ?? '');
        $phone = $this->db->escape($data['phone'] ?? '');
        $email = $this->db->escape($data['email'] ?? '');
        $address = $this->db->escape($data['address'] ?? '');
        $join_date = $this->db->escape($data['join_date'] ?? '');
        $photo = $this->db->escape($files['photo']['name'] ?? '');
        $sql = "INSERT INTO employees (name, position, phone, email, address, join_date, photo)
                VALUES ('$name','$position','$phone','$email','$address','$join_date','$photo')";
        return $this->db->query($sql);
    }

    public function updateEmployee($data, $files = []) {
        $id = intval($data['id'] ?? 0);
        $name = $this->db->escape($data['name'] ?? '');
        $position = $this->db->escape($data['position'] ?? '');
        $phone = $this->db->escape($data['phone'] ?? '');
        $email = $this->db->escape($data['email'] ?? '');
        $address = $this->db->escape($data['address'] ?? '');
        $join_date = $this->db->escape($data['join_date'] ?? '');
        $photo_sql = "";
        if (!empty($files['photo']) && $files['photo']['error'] == 0) {
            $photo_name = $this->db->escape($files['photo']['name']);
            $photo_sql = ", photo='$photo_name'";
            // TODO: move_uploaded_file if you want
        }
        $sql = "UPDATE employees SET name='$name', position='$position', phone='$phone', email='$email', address='$address', join_date='$join_date' $photo_sql WHERE id='$id'";
        return $this->db->query($sql);
    }

    public function deleteEmployee($id) {
        $id = intval($id);
        return $this->db->query("DELETE FROM employees WHERE id='$id'");
    }
}
?>
