<?php
namespace app\models;

use app\app;

class addresses
{
    public static function init()
    {
        app::$db->exec("CREATE TABLE IF NOT EXISTS addresses (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER REFERENCES users(id),
            name TEXT NOT NULL,
            company TEXT,
            addressLine1 TEXT NOT NULL,
            addressLine2 TEXT NOT NULL,
            city TEXT NOT NULL,
            state TEXT NOT NULL,
            zip TEXT NOT NULL,
            phone TEXT
        )");
    }

    public static function validatePost($type = "")
    {
        $name         = $_POST["{$type}name"];
        $company      = $_POST["{$type}company"] ?? null;
        $addressLine2 = $_POST["{$type}addressLine2"] ?? null;
        $addressLine1 = $_POST["{$type}addressLine1"];
        $city         = $_POST["{$type}city"];
        $state        = $_POST["{$type}state"];
        $zip          = $_POST["{$type}zip"];
        $phone        = $_POST["{$type}phone"];
        $email        = $_POST["{$type}email"] ?? null; // Assuming email is part of the form

        // check all required fields are set
        if (empty($name) || empty($addressLine1) || empty($city) || empty($state) || empty($zip) || empty($phone)) {
            $_SESSION['error'] = "Missing required {$type} information.";
            return ["error" => "Missing required {$type} information."];
        }

        // Set up the cURL request
        $ch = curl_init();

        // Set the Shippo API endpoint for address validation
        $url = sprintf(
            'https://api.goshippo.com/v2/addresses/validate?address_line_1=%s&city_locality=%s&state_province=%s&postal_code=%s&country_code=US&organization=%s',
            urlencode($addressLine1),
            urlencode($city),
            urlencode($state),
            urlencode($zip),
            urlencode($company)
        );

        // Set the cURL options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: ShippoToken ' . $_ENV['SHIPPO_API_KEY'],
        ]);

        // Execute the cURL request
        $response = curl_exec($ch);
        curl_close($ch);
        $validated_address = json_decode($response, true);
        // print_r($response);
        // Check the status of the validation
        if (isset($validated_address['analysis']['validation_result']['value']) && $validated_address['analysis']['validation_result']['value'] === 'valid') {
            $result = [
                'name'         => $name,
                'company'      => $company,
                "addressLine1" => $addressLine1,
                "addressLine2" => $addressLine2,
                "city"         => $city,
                "state"        => $state,
                "zip"          => $zip,
                'phone'        => $phone,
            ];
        } elseif (isset($validated_address['recommended_address']['confidence_result']['score']) && $validated_address['recommended_address']['confidence_result']['score'] === 'high') {
            $recommended = $validated_address['recommended_address'];
            $result      = [
                'name'         => $name,
                'company'      => $company,
                "addressLine1" => $recommended['address_line_1'],
                "addressLine2" => $addressLine2,
                "city"         => $recommended['city_locality'],
                "state"        => $recommended['state_province'],
                "zip"          => $recommended['postal_code'],
                'phone'        => $phone,
            ];
        } else {
            $error_message = "Address is invalid.";
            if (isset($validated_address['analysis']['validation_result']['reasons'])) {
                foreach ($validated_address['analysis']['validation_result']['reasons'] as $reason) {
                    if ($reason['type'] === 'error') {
                        $error_message = $reason['description'];
                        break;
                    }
                }
            }
            $_SESSION['error'] = $error_message;
            return ["error" => $error_message];
        }
        return $result;
    }

    public static function updateUserIdById($bill_id, $user_id)
    {
        $query = "UPDATE addresses SET user_id = :user_id WHERE id = :bill_id";
        $stmt  = app::$db->prepare($query);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->bindParam(':bill_id', $bill_id);
        $stmt->execute();
    }

    public static function getByUserId($user_id)
    {
        $query = "SELECT * FROM addresses WHERE user_id = :user_id";
        $stmt  = app::$db->prepare($query);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->execute();
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public static function getById($id)
    {
        $query = "SELECT * FROM addresses WHERE id = :id";
        $stmt  = app::$db->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        return $stmt->fetch(\PDO::FETCH_ASSOC);
    }
    public static function updateById($id, $name, $company, $addressLine1, $addressLine2, $city, $state, $zip, $phone)
    {
        $query = "UPDATE addresses SET
            name = :name,
            company = :company,
            addressLine1 = :addressLine1,
            addressLine2 = :addressLine2,
            city = :city,
            state = :state,
            zip = :zip,
            phone = :phone
            WHERE id = :id";

        $stmt = app::$db->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':company', $company);
        $stmt->bindParam(':addressLine1', $addressLine1);
        $stmt->bindParam(':addressLine2', $addressLine2);
        $stmt->bindParam(':city', $city);
        $stmt->bindParam(':state', $state);
        $stmt->bindParam(':zip', $zip);
        $stmt->bindParam(':phone', $phone);
        $stmt->execute();
    }

    public static function deleteById($id)
    {
        $query = "DELETE FROM addresses WHERE id = :id";
        $stmt  = app::$db->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
    }

    public static function add($user_id, $name, $company, $addressLine1, $addressLine2, $city, $state, $zip, $phone)
    {
        $query = "INSERT INTO addresses (
            user_id,
            name,
            company,
            addressLine1,
            addressLine2,
            city,
            state,
            zip,
            phone
        ) VALUES (
            :user_id,
            :name,
            :company,
            :addressLine1,
            :addressLine2,
            :city,
            :state,
            :zip,
            :phone
        )";
        $stmt = app::$db->prepare($query);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':company', $company);
        $stmt->bindParam(':addressLine1', $addressLine1);
        $stmt->bindParam(':addressLine2', $addressLine2);
        $stmt->bindParam(':city', $city);
        $stmt->bindParam(':state', $state);
        $stmt->bindParam(':zip', $zip);
        $stmt->bindParam(':phone', $phone);
        $stmt->execute();
        return app::$db->lastInsertId();
    }

}
