<?php
require_once __DIR__ . '/../models/Guesthouse.php';
require_once __DIR__ . '/../models/GuesthousePhoto.php';
require_once __DIR__ . '/../helpers/Response.php';
require_once __DIR__ . '/../middlewares/AuthMiddleware.php';
require_once __DIR__ . '/../helpers/Validator.php';

class GuesthouseController
{
    private $db;
    private $guesthouse;

    public function __construct($db)
    {
        $this->db = $db;
        $this->guesthouse = new Guesthouse($db);
    }

    public function create()
    {
        try {
            $user = AuthMiddleware::authenticate();

            $input = file_get_contents("php://input");
            $data = json_decode($input, true);

            if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
                Response::error("Invalid JSON data provided.", 400);
                return;
            }

            $rules = [
                'name' => 'required',
                'accommodation_type' => 'required',
                'responsible_name' => 'required',
                'phone' => 'required',
                'city' => 'required',
                'neighborhood' => 'required',
                'address' => 'required',
                'price' => 'required'
            ];

            $errors = Validator::validate($data, $rules);

            if (!empty($errors)) {
                Response::error("Validation Error", 400, $errors);
                return;
            }

            $this->guesthouse->user_id = $user->id;
            $this->guesthouse->name = trim($data['name']);
            $this->guesthouse->accommodation_type = trim($data['accommodation_type']);
            $this->guesthouse->responsible_name = trim($data['responsible_name']);
            $this->guesthouse->phone = trim($data['phone']);
            $this->guesthouse->email = trim($data['email'] ?? '');
            $this->guesthouse->city = trim($data['city']);
            $this->guesthouse->neighborhood = trim($data['neighborhood']);
            $this->guesthouse->address = trim($data['address']);
            $this->guesthouse->gps_coordinates = trim($data['gps_coordinates'] ?? '');
            $this->guesthouse->total_rooms = $data['total_rooms'] ?? null;
            $this->guesthouse->capacity = $data['capacity'] ?? null;
            $this->guesthouse->price_per_hour = $data['price_per_hour'] ?? null;
            $this->guesthouse->price_per_2_hours = $data['price_per_2_hours'] ?? null;
            $this->guesthouse->price_per_night = $data['price_per_night'] ?? null;
            $this->guesthouse->price = $data['price'];
            $this->guesthouse->accepts_mpesa = $data['accepts_mpesa'] ?? 0;
            $this->guesthouse->accepts_emola = $data['accepts_emola'] ?? 0;
            $this->guesthouse->accepts_visa = $data['accepts_visa'] ?? 0;
            $this->guesthouse->preferred_contact_method = trim($data['preferred_contact_method'] ?? 'Telefone');
            $this->guesthouse->accepts_online_reserves = $data['accepts_online_reserves'] ?? 1;
            $this->guesthouse->accepts_commission = $data['accepts_commission'] ?? 1;
            $this->guesthouse->description = trim($data['description'] ?? '');
            $this->guesthouse->has_wifi = $data['has_wifi'] ?? 0;
            $this->guesthouse->has_parking = $data['has_parking'] ?? 0;
            $this->guesthouse->has_ac = $data['has_ac'] ?? 0;
            $this->guesthouse->has_security = $data['has_security'] ?? 0;
            $this->guesthouse->has_cleaning = $data['has_cleaning'] ?? 0;

            if ($this->guesthouse->create()) {
                Response::success("Guesthouse created successfully.", ["id" => $this->guesthouse->id]);
            } else {
                Response::error("Unable to create guesthouse. Please verify ENUM values (accommodation_type: " . $this->guesthouse->accommodation_type . ", preferred_contact_method: " . $this->guesthouse->preferred_contact_method . ")", 400);
            }
        } catch (Exception $e) {
            Response::error("An unexpected error occurred: " . $e->getMessage(), 500);
        }
    }

    public function index()
    {
        $stmt = $this->guesthouse->getAll();
        $num = $stmt->rowCount();

        if ($num >= 0) {
            $guesthouses_arr = array();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $photoUrl = $row['photo_url'];
                if ($photoUrl) {
                    $fileName = basename($photoUrl);
                    $row['photo_url'] = "https://www.esquinaki.co.mz/uploads/" . $fileName;
                }

                // Format numeric values
                $row['avg_rating'] = $row['avg_rating'] ? (float) $row['avg_rating'] : 0.0;
                $row['reviews_count'] = (int) $row['reviews_count'];

                // Cast boolean fields
                $boolFields = [
                    'has_wifi',
                    'has_parking',
                    'has_ac',
                    'has_security',
                    'has_cleaning',
                    'accepts_mpesa',
                    'accepts_emola',
                    'accepts_visa',
                    'accepts_online_reserves',
                    'accepts_commission'
                ];
                foreach ($boolFields as $field) {
                    if (isset($row[$field])) {
                        $row[$field] = (int) $row[$field];
                    }
                }

                // Cast numeric price fields
                $priceFields = [
                    'price',
                    'price_per_hour',
                    'price_per_2_hours',
                    'price_per_night',
                    'total_rooms',
                    'capacity'
                ];
                foreach ($priceFields as $field) {
                    if (isset($row[$field]) && $row[$field] !== null) {
                        $row[$field] = is_numeric($row[$field]) ? (float) $row[$field] : null;
                    }
                }

                array_push($guesthouses_arr, $row);
            }
            Response::success("Guesthouses found.", $guesthouses_arr);
        } else {
            Response::success("No guesthouses found.", []);
        }
    }

    public function my_guesthouses()
    {
        $user = AuthMiddleware::authenticate();

        $stmt = $this->guesthouse->getByUserId($user->id);
        $num = $stmt->rowCount();

        if ($num >= 0) {
            $guesthouses_arr = array();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $photoUrl = $row['photo_url'];
                if ($photoUrl) {
                    $fileName = basename($photoUrl);
                    $row['photo_url'] = "https://www.esquinaki.co.mz/uploads/" . $fileName;
                }

                // Format numeric values
                $row['avg_rating'] = $row['avg_rating'] ? (float) $row['avg_rating'] : 0.0;
                $row['reviews_count'] = (int) $row['reviews_count'];

                // Cast boolean fields
                $boolFields = [
                    'has_wifi',
                    'has_parking',
                    'has_ac',
                    'has_security',
                    'has_cleaning',
                    'accepts_mpesa',
                    'accepts_emola',
                    'accepts_visa',
                    'accepts_online_reserves',
                    'accepts_commission'
                ];
                foreach ($boolFields as $field) {
                    if (isset($row[$field])) {
                        $row[$field] = (int) $row[$field];
                    }
                }

                // Cast numeric price fields
                $priceFields = [
                    'price',
                    'price_per_hour',
                    'price_per_2_hours',
                    'price_per_night',
                    'total_rooms',
                    'capacity'
                ];
                foreach ($priceFields as $field) {
                    if (isset($row[$field]) && $row[$field] !== null) {
                        $row[$field] = is_numeric($row[$field]) ? (float) $row[$field] : null;
                    }
                }

                array_push($guesthouses_arr, $row);
            }
            Response::success("My guesthouses found.", $guesthouses_arr);
        } else {
            Response::success("You have no registered guesthouses.", []);
        }
    }

    public function update()
    {
        try {
            $user = AuthMiddleware::authenticate();

            $input = file_get_contents("php://input");
            $data = json_decode($input, true);

            if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
                Response::error("Invalid JSON data provided.", 400);
                return;
            }

            if (!isset($data['id'])) {
                Response::error("Guesthouse ID is required for update.", 400);
                return;
            }

            // Verify ownership
            $stmt = $this->guesthouse->getById($data['id']);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$row) {
                Response::error("Guesthouse not found.", 404);
                return;
            }

            if ($row['user_id'] != $user->id) {
                Response::error("Unauthorized to update this guesthouse.", 403);
                return;
            }

            $this->guesthouse->id = $data['id'];
            $this->guesthouse->name = $data['name'] ?? $row['name'];
            $this->guesthouse->accommodation_type = $data['accommodation_type'] ?? $row['accommodation_type'];
            $this->guesthouse->responsible_name = $data['responsible_name'] ?? $row['responsible_name'];
            $this->guesthouse->phone = $data['phone'] ?? $row['phone'];
            $this->guesthouse->email = $data['email'] ?? $row['email'];
            $this->guesthouse->city = $data['city'] ?? $row['city'];
            $this->guesthouse->neighborhood = $data['neighborhood'] ?? $row['neighborhood'];
            $this->guesthouse->address = $data['address'] ?? $row['address'];
            $this->guesthouse->gps_coordinates = $data['gps_coordinates'] ?? $row['gps_coordinates'];
            $this->guesthouse->total_rooms = $data['total_rooms'] ?? $row['total_rooms'];
            $this->guesthouse->capacity = $data['capacity'] ?? $row['capacity'];
            $this->guesthouse->price_per_hour = $data['price_per_hour'] ?? $row['price_per_hour'];
            $this->guesthouse->price_per_2_hours = $data['price_per_2_hours'] ?? $row['price_per_2_hours'];
            $this->guesthouse->price_per_night = $data['price_per_night'] ?? $row['price_per_night'];
            $this->guesthouse->price = $data['price'] ?? $row['price'];
            $this->guesthouse->accepts_mpesa = $data['accepts_mpesa'] ?? $row['accepts_mpesa'];
            $this->guesthouse->accepts_emola = $data['accepts_emola'] ?? $row['accepts_emola'];
            $this->guesthouse->accepts_visa = $data['accepts_visa'] ?? $row['accepts_visa'];
            $this->guesthouse->preferred_contact_method = $data['preferred_contact_method'] ?? $row['preferred_contact_method'];
            $this->guesthouse->accepts_online_reserves = $data['accepts_online_reserves'] ?? $row['accepts_online_reserves'];
            $this->guesthouse->accepts_commission = $data['accepts_commission'] ?? $row['accepts_commission'];
            $this->guesthouse->description = $data['description'] ?? $row['description'];
            $this->guesthouse->has_wifi = $data['has_wifi'] ?? $row['has_wifi'];
            $this->guesthouse->has_parking = $data['has_parking'] ?? $row['has_parking'];
            $this->guesthouse->has_ac = $data['has_ac'] ?? $row['has_ac'];
            $this->guesthouse->has_security = $data['has_security'] ?? $row['has_security'];
            $this->guesthouse->has_cleaning = $data['has_cleaning'] ?? $row['has_cleaning'];

            if ($this->guesthouse->update()) {
                Response::success("Guesthouse updated successfully.");
            } else {
                Response::error("Unable to update guesthouse.", 503);
            }
        } catch (Exception $e) {
            Response::error("An unexpected error occurred: " . $e->getMessage(), 500);
        }
    }

    public function delete()
    {
        $user = AuthMiddleware::authenticate();
        $data = json_decode(file_get_contents("php://input"), true);

        if (!isset($data['id'])) {
            Response::error("Guesthouse ID is required for deletion.", 400);
        }

        // Verify ownership
        $stmt = $this->guesthouse->getById($data['id']);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            Response::error("Guesthouse not found.", 404);
        }

        if ($row['user_id'] != $user->id) {
            Response::error("Unauthorized to delete this guesthouse.", 403);
        }

        $this->guesthouse->id = $data['id'];

        if ($this->guesthouse->delete()) {
            Response::success("Guesthouse deleted successfully.");
        } else {
            Response::error("Unable to delete guesthouse.", 503);
        }
    }
}
?>