<?php
/**
 * OTA Sync Controller
 * Handles OTA integration endpoints
 */

class OTASyncController {
    private $db;
    private $config;
    private $ota_service;

    public function __construct($db, $config, $ota_service) {
        $this->db = $db;
        $this->config = $config;
        $this->ota_service = $ota_service;
    }

    /**
     * POST /api/ota/sync-airbnb
     * Sync bookings from Airbnb
     */
    public function syncAirbnb($property_id) {
        return $this->ota_service->syncAirbnbBookings($property_id);
    }

    /**
     * POST /api/ota/sync-booking
     * Sync bookings from Booking.com
     */
    public function syncBookingCom($property_id) {
        return $this->ota_service->syncBookingComBookings($property_id);
    }

    /**
     * GET /api/ota/sync-status
     * Get sync status
     */
    public function getSyncStatus($property_id) {
        return $this->ota_service->getSyncStatus($property_id);
    }

    /**
     * GET /api/ota/calendar
     * Get calendar with booked dates
     */
    public function getCalendar($property_id, $month = null, $year = null) {
        return $this->ota_service->getCalendar($property_id, $month, $year);
    }

    /**
     * GET /api/ota/connections
     * Get OTA connections for property
     */
    public function getConnections($property_id) {
        try {
            $stmt = $this->db->prepare("
                SELECT * FROM ota_connections
                WHERE property_id = ?
            ");
            $stmt->execute([$property_id]);
            $connections = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return [
                'success' => true,
                'connections' => $connections
            ];

        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Error fetching connections'];
        }
    }

    /**
     * POST /api/ota/connect-airbnb
     * Connect Airbnb
     */
    public function connectAirbnb($property_id, $api_key) {
        try {
            // Check if already connected
            $stmt = $this->db->prepare("
                SELECT id FROM ota_connections
                WHERE property_id = ? AND platform = 'airbnb'
            ");
            $stmt->execute([$property_id]);
            if ($stmt->fetch()) {
                return ['success' => false, 'message' => 'Airbnb already connected'];
            }

            // Create connection
            $stmt = $this->db->prepare("
                INSERT INTO ota_connections (property_id, platform, api_key, active, created_at)
                VALUES (?, 'airbnb', ?, 1, NOW())
            ");
            $stmt->execute([$property_id, $api_key]);

            return ['success' => true, 'message' => 'Airbnb connected'];

        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Error connecting Airbnb'];
        }
    }

    /**
     * POST /api/ota/connect-booking
     * Connect Booking.com
     */
    public function connectBooking($property_id, $api_key) {
        try {
            // Check if already connected
            $stmt = $this->db->prepare("
                SELECT id FROM ota_connections
                WHERE property_id = ? AND platform = 'booking'
            ");
            $stmt->execute([$property_id]);
            if ($stmt->fetch()) {
                return ['success' => false, 'message' => 'Booking.com already connected'];
            }

            // Create connection
            $stmt = $this->db->prepare("
                INSERT INTO ota_connections (property_id, platform, api_key, active, created_at)
                VALUES (?, 'booking', ?, 1, NOW())
            ");
            $stmt->execute([$property_id, $api_key]);

            return ['success' => true, 'message' => 'Booking.com connected'];

        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Error connecting Booking.com'];
        }
    }

    /**
     * POST /api/ota/auto-sync
     * Start auto-sync for all properties (cron job)
     */
    public function autoSync() {
        try {
            $stmt = $this->db->prepare("
                SELECT DISTINCT property_id FROM ota_connections WHERE active = 1
            ");
            $stmt->execute();
            $properties = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $synced = 0;
            foreach ($properties as $prop) {
                // Sync from each platform
                $this->ota_service->syncAirbnbBookings($prop['property_id']);
                $this->ota_service->syncBookingComBookings($prop['property_id']);
                $synced++;
            }

            return [
                'success' => true,
                'message' => "Synced $synced properties",
                'synced_count' => $synced
            ];

        } catch (Exception $e) {
            error_log('Auto-sync error: ' . $e->getMessage());
            return ['success' => false, 'message' => 'Auto-sync failed'];
        }
    }
}
