<?php
/**
 * Parcel Model
 */

class Parcel {
    private $pdo;

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

    /**
     * Create new parcel
     */
    public function create($data) {
        $tracking_code = Utils::generateTrackingCode();
        
        $stmt = $this->pdo->prepare("
            INSERT INTO parcels (
                tracking_code, sender_name, sender_email, sender_phone, sender_address,
                sender_city, sender_country, receiver_name, receiver_email, receiver_phone,
                receiver_address, receiver_city, receiver_country, package_description,
                package_weight, package_dimensions, service_type, status, current_location,
                current_latitude, current_longitude, estimated_delivery, notes
            ) VALUES (
                :tracking_code, :sender_name, :sender_email, :sender_phone, :sender_address,
                :sender_city, :sender_country, :receiver_name, :receiver_email, :receiver_phone,
                :receiver_address, :receiver_city, :receiver_country, :package_description,
                :package_weight, :package_dimensions, :service_type, :status, :current_location,
                :current_latitude, :current_longitude, :estimated_delivery, :notes
            )
        ");

        $stmt->execute([
            ':tracking_code' => $tracking_code,
            ':sender_name' => $data['sender_name'] ?? '',
            ':sender_email' => $data['sender_email'] ?? '',
            ':sender_phone' => $data['sender_phone'] ?? '',
            ':sender_address' => $data['sender_address'] ?? '',
            ':sender_city' => $data['sender_city'] ?? '',
            ':sender_country' => $data['sender_country'] ?? '',
            ':receiver_name' => $data['receiver_name'] ?? '',
            ':receiver_email' => $data['receiver_email'] ?? '',
            ':receiver_phone' => $data['receiver_phone'] ?? '',
            ':receiver_address' => $data['receiver_address'] ?? '',
            ':receiver_city' => $data['receiver_city'] ?? '',
            ':receiver_country' => $data['receiver_country'] ?? '',
            ':package_description' => $data['package_description'] ?? '',
            ':package_weight' => $data['package_weight'] ?? 0,
            ':package_dimensions' => $data['package_dimensions'] ?? '',
            ':service_type' => $data['service_type'] ?? 'air_freight',
            ':status' => $data['status'] ?? 'pending',
            ':current_location' => $data['current_location'] ?? '',
            ':current_latitude' => $data['current_latitude'] ?? null,
            ':current_longitude' => $data['current_longitude'] ?? null,
            ':estimated_delivery' => $data['estimated_delivery'] ?? null,
            ':notes' => $data['notes'] ?? ''
        ]);

        $parcel_id = $this->pdo->lastInsertId();

        // Create initial update record
        $this->addUpdate($parcel_id, $data['status'] ?? 'pending', $data['current_location'] ?? '', 'Parcel created', $data['current_latitude'] ?? null, $data['current_longitude'] ?? null);

        return ['success' => true, 'parcel_id' => $parcel_id, 'tracking_code' => $tracking_code];
    }

    /**
     * Get parcel by tracking code
     */
    public function getByTrackingCode($tracking_code) {
        $stmt = $this->pdo->prepare("SELECT * FROM parcels WHERE tracking_code = :tracking_code");
        $stmt->execute([':tracking_code' => $tracking_code]);
        return $stmt->fetch();
    }

    /**
     * Get parcel by ID
     */
    public function getById($id) {
        $stmt = $this->pdo->prepare("SELECT * FROM parcels WHERE id = :id");
        $stmt->execute([':id' => $id]);
        return $stmt->fetch();
    }

    /**
     * Get all parcels
     */
    public function getAll($limit = 50, $offset = 0) {
        $stmt = $this->pdo->prepare("
            SELECT * FROM parcels 
            ORDER BY created_at DESC 
            LIMIT :limit OFFSET :offset
        ");
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    /**
     * Get parcel count
     */
    public function getCount() {
        $stmt = $this->pdo->query("SELECT COUNT(*) as count FROM parcels");
        $result = $stmt->fetch();
        return $result['count'];
    }

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

        foreach ($data as $key => $value) {
            $fields[] = "$key = :$key";
            $params[":$key"] = $value;
        }

        $sql = "UPDATE parcels SET " . implode(', ', $fields) . " WHERE id = :id";
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute($params);
    }

    /**
     * Delete parcel
     */
    public function delete($id) {
        $stmt = $this->pdo->prepare("DELETE FROM parcels WHERE id = :id");
        return $stmt->execute([':id' => $id]);
    }

    /**
     * Add update to parcel
     */
    public function addUpdate($parcel_id, $status, $location, $description = '', $latitude = null, $longitude = null) {
        $stmt = $this->pdo->prepare("
            INSERT INTO parcel_updates (parcel_id, status, location, description, latitude, longitude)
            VALUES (:parcel_id, :status, :location, :description, :latitude, :longitude)
        ");

        $result = $stmt->execute([
            ':parcel_id' => $parcel_id,
            ':status' => $status,
            ':location' => $location,
            ':description' => $description,
            ':latitude' => $latitude,
            ':longitude' => $longitude
        ]);

        // Update parcel status and location
        if ($result) {
            $updateData = [
                'status' => $status,
                'current_location' => $location
            ];
            if ($latitude !== null) $updateData['current_latitude'] = $latitude;
            if ($longitude !== null) $updateData['current_longitude'] = $longitude;

            $this->update($parcel_id, $updateData);
        }

        return $result;
    }

    /**
     * Get parcel updates
     */
    public function getUpdates($parcel_id) {
        $stmt = $this->pdo->prepare("
            SELECT * FROM parcel_updates 
            WHERE parcel_id = :parcel_id 
            ORDER BY created_at DESC
        ");
        $stmt->execute([':parcel_id' => $parcel_id]);
        return $stmt->fetchAll();
    }

    /**
     * Get statistics
     */
    public function getStats() {
        $stats = [];

        // Total parcels
        $stmt = $this->pdo->query("SELECT COUNT(*) as count FROM parcels");
        $stats['total'] = $stmt->fetch()['count'];

        // By status
        $stmt = $this->pdo->query("
            SELECT status, COUNT(*) as count FROM parcels 
            GROUP BY status
        ");
        $stats['by_status'] = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

        // Delivered today
        $stmt = $this->pdo->query("
            SELECT COUNT(*) as count FROM parcels 
            WHERE status = 'delivered' AND DATE(actual_delivery) = CURDATE()
        ");
        $stats['delivered_today'] = $stmt->fetch()['count'];

        return $stats;
    }
}
