<?php

class PickupLocation {
    private $pdo;

    public function __construct() {
        global $pdo;
        $this->pdo = $pdo;
    }

    public function all($activeOnly = true) {
        $sql = "SELECT * FROM pickup_locations";
        if ($activeOnly) {
            $sql .= " WHERE active = 1";
        }
        $sql .= " ORDER BY sort_order, name";
        $stmt = $this->pdo->query($sql);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function find($id) {
        $stmt = $this->pdo->prepare("SELECT * FROM pickup_locations WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function create($data) {
        $stmt = $this->pdo->prepare("INSERT INTO pickup_locations (name, address, sort_order, active) VALUES (?, ?, ?, ?)");
        $stmt->execute([
            $data['name'],
            $data['address'] ?? null,
            $data['sort_order'] ?? 0,
            $data['active'] ?? 1
        ]);
        return $this->pdo->lastInsertId();
    }

    public function update($id, $data) {
        $stmt = $this->pdo->prepare("UPDATE pickup_locations SET name = ?, address = ?, sort_order = ?, active = ? WHERE id = ?");
        return $stmt->execute([
            $data['name'],
            $data['address'] ?? null,
            $data['sort_order'] ?? 0,
            $data['active'] ?? 1,
            $id
        ]);
    }

    public function delete($id) {
        $stmt = $this->pdo->prepare("DELETE FROM pickup_locations WHERE id = ?");
        return $stmt->execute([$id]);
    }
}
