<?php
/**
 * Operator Model
 * Handles bus operator (company) data
 */

class Operator {
    private $conn;
    private $table_name = "operators";

    public $id;
    public $name;
    public $contact_person;
    public $email;
    public $phone;
    public $mobile;
    public $fax;
    public $address;
    public $site;
    public $type;
    public $description;
    public $rc;
    public $nif;
    public $ai;
    public $exonerer;
    public $code_auxiliaire;
    public $statut;
    public $creer_par;
    public $date_creation;
    public $modifier_par;
    public $date_modification;

    public function __construct($db) {
        $this->conn = $db;
    }

    /**
     * Get operator by ID
     */
    public function getById($id) {
        $query = "SELECT * FROM " . $this->table_name . " WHERE id = :id LIMIT 1";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * Get all operators
     */
    public function getAll($filters = []) {
        $query = "SELECT o.*, COUNT(b.id) as buses_count
                  FROM " . $this->table_name . " o
                  LEFT JOIN buses b ON o.id = b.id_operateur AND b.status = 'Active'
                  GROUP BY o.id";

        $conditions = [];
        $params = [];

        if (isset($filters['statut'])) {
            $conditions[] = "o.statut = :statut";
            $params[':statut'] = $filters['statut'];
        }

        if (isset($filters['type'])) {
            $conditions[] = "o.type = :type";
            $params[':type'] = $filters['type'];
        }

        if (isset($filters['name'])) {
            $conditions[] = "o.name LIKE :name";
            $params[':name'] = '%' . $filters['name'] . '%';
        }

        if (!empty($conditions)) {
            $query .= " HAVING " . implode(" AND ", $conditions);
        }

        $query .= " ORDER BY o.name ASC";

        $stmt = $this->conn->prepare($query);

        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }

        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Create new operator
     */
    public function create($data) {
        $query = "INSERT INTO " . $this->table_name . "
                  (name, contact_person, email, phone, mobile, fax, address, site, type, description, rc, nif, ai, exonerer, code_auxiliaire, statut, creer_par)
                  VALUES (:name, :contact_person, :email, :phone, :mobile, :fax, :address, :site, :type, :description, :rc, :nif, :ai, :exonerer, :code_auxiliaire, :statut, :creer_par)";

        $stmt = $this->conn->prepare($query);

        $stmt->bindParam(':name', $data['name']);
        $stmt->bindParam(':contact_person', $data['contact_person'] ?? null);
        $stmt->bindParam(':email', $data['email'] ?? null);
        $stmt->bindParam(':phone', $data['phone'] ?? null);
        $stmt->bindParam(':mobile', $data['mobile'] ?? null);
        $stmt->bindParam(':fax', $data['fax'] ?? null);
        $stmt->bindParam(':address', $data['address'] ?? null);
        $stmt->bindParam(':site', $data['site'] ?? null);
        $stmt->bindParam(':type', $data['type'] ?? 'prive');
        $stmt->bindParam(':description', $data['description'] ?? null);
        $stmt->bindParam(':rc', $data['rc'] ?? null);
        $stmt->bindParam(':nif', $data['nif'] ?? null);
        $stmt->bindParam(':ai', $data['ai'] ?? null);
        $stmt->bindParam(':exonerer', $data['exonerer'] ?? 'Non');
        $stmt->bindParam(':code_auxiliaire', $data['code_auxiliaire'] ?? null);
        $stmt->bindParam(':statut', $data['statut'] ?? 'actif');
        $stmt->bindParam(':creer_par', $data['creer_par'] ?? null);

        if ($stmt->execute()) {
            return $this->conn->lastInsertId();
        }

        return false;
    }

    /**
     * Update operator
     */
    public function update($id, $data) {
        $fields = [];
        $params = [':id' => $id];

        if (isset($data['name'])) {
            $fields[] = "name = :name";
            $params[':name'] = $data['name'];
        }

        if (isset($data['contact_person'])) {
            $fields[] = "contact_person = :contact_person";
            $params[':contact_person'] = $data['contact_person'];
        }

        if (isset($data['email'])) {
            $fields[] = "email = :email";
            $params[':email'] = $data['email'];
        }

        if (isset($data['phone'])) {
            $fields[] = "phone = :phone";
            $params[':phone'] = $data['phone'];
        }

        if (isset($data['mobile'])) {
            $fields[] = "mobile = :mobile";
            $params[':mobile'] = $data['mobile'];
        }

        if (isset($data['fax'])) {
            $fields[] = "fax = :fax";
            $params[':fax'] = $data['fax'];
        }

        if (isset($data['address'])) {
            $fields[] = "address = :address";
            $params[':address'] = $data['address'];
        }

        if (isset($data['site'])) {
            $fields[] = "site = :site";
            $params[':site'] = $data['site'];
        }

        if (isset($data['type'])) {
            $fields[] = "type = :type";
            $params[':type'] = $data['type'];
        }

        if (isset($data['description'])) {
            $fields[] = "description = :description";
            $params[':description'] = $data['description'];
        }

        if (isset($data['rc'])) {
            $fields[] = "rc = :rc";
            $params[':rc'] = $data['rc'];
        }

        if (isset($data['nif'])) {
            $fields[] = "nif = :nif";
            $params[':nif'] = $data['nif'];
        }

        if (isset($data['ai'])) {
            $fields[] = "ai = :ai";
            $params[':ai'] = $data['ai'];
        }

        if (isset($data['exonerer'])) {
            $fields[] = "exonerer = :exonerer";
            $params[':exonerer'] = $data['exonerer'];
        }

        if (isset($data['code_auxiliaire'])) {
            $fields[] = "code_auxiliaire = :code_auxiliaire";
            $params[':code_auxiliaire'] = $data['code_auxiliaire'];
        }

        if (isset($data['statut'])) {
            $fields[] = "statut = :statut";
            $params[':statut'] = $data['statut'];
        }

        if (isset($data['modifier_par'])) {
            $fields[] = "modifier_par = :modifier_par";
            $params[':modifier_par'] = $data['modifier_par'];
        }

        if (empty($fields)) {
            return false;
        }

        $query = "UPDATE " . $this->table_name . "
                  SET " . implode(", ", $fields) . ", date_modification = NOW()
                  WHERE id = :id";

        $stmt = $this->conn->prepare($query);

        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }

        return $stmt->execute();
    }

    /**
     * Delete operator
     */
    public function delete($id) {
        // Check if operator has buses
        $query = "SELECT COUNT(*) as count FROM buses WHERE operator_id = :id";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($result['count'] > 0) {
            return false; // Cannot delete operator with buses
        }

        $query = "DELETE FROM " . $this->table_name . " WHERE id = :id";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $id);
        return $stmt->execute();
    }

    /**
     * Check if name exists
     */
    public function nameExists($name, $exclude_id = null) {
        $query = "SELECT id FROM " . $this->table_name . " WHERE name = :name";
        $params = [':name' => $name];

        if ($exclude_id) {
            $query .= " AND id != :exclude_id";
            $params[':exclude_id'] = $exclude_id;
        }

        $stmt = $this->conn->prepare($query);

        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }

        $stmt->execute();
        return $stmt->rowCount() > 0;
    }

    /**
     * Get operator statistics
     */
    public function getStats() {
        $query = "SELECT
                    COUNT(*) as total_operators,
                    SUM(CASE WHEN statut = 'actif' THEN 1 ELSE 0 END) as active_operators,
                    AVG(buses_per_operator) as avg_buses_per_operator
                  FROM (
                      SELECT o.id, COUNT(b.id) as buses_per_operator
                      FROM " . $this->table_name . " o
                      LEFT JOIN buses b ON o.id = b.operator_id AND b.status = 'Active'
                      GROUP BY o.id
                  ) as operator_stats";

        $stmt = $this->conn->prepare($query);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
}
?>
