<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../models/Client.php';

$database = new Database();
$db = $database->getConnection();

$client = new Client($db);

$request_method = $_SERVER['REQUEST_METHOD'];

switch($request_method) {
    case 'GET':
        if(isset($_GET['id'])) {
            $client->id = $_GET['id'];
            $client->readOne();
            
            if($client->email != null) {
                $client_arr = array(
                    "id" => $client->id,
                    "company_name" => $client->company_name,
                    "y_tunnus" => $client->y_tunnus,
                    "first_name" => $client->first_name,
                    "last_name" => $client->last_name,
                    "email" => $client->email,
                    "phone" => $client->phone,
                    "address" => $client->address,
                    "city" => $client->city,
                    "state" => $client->state,
                    "postal_code" => $client->postal_code,
                    "country" => $client->country,
                    "notes" => $client->notes,
                    "hour_price" => $client->hour_price,
                    "created_at" => $client->created_at,
                    "updated_at" => $client->updated_at
                );
                
                http_response_code(200);
                echo json_encode($client_arr);
            } else {
                http_response_code(404);
                echo json_encode(array("message" => "Client not found."));
            }
        } elseif(isset($_GET['search'])) {
            $search_term = $_GET['search'];
            $stmt = $client->search($search_term);
            $num = $stmt->rowCount();
            
            if($num > 0) {
                $clients_arr = array();
                $clients_arr["records"] = array();
                
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    extract($row);
                    
                    $client_item = array(
                        "id" => $id,
                        "company_name" => $company_name,
                        "first_name" => $first_name,
                        "last_name" => $last_name,
                        "email" => $email,
                        "phone" => $phone,
                        "address" => $address,
                        "city" => $city,
                        "state" => $state,
                        "postal_code" => $postal_code,
                        "country" => $country,
                        "notes" => $notes,
                        "created_at" => $created_at,
                        "updated_at" => $updated_at
                    );
                    
                    array_push($clients_arr["records"], $client_item);
                }
                
                http_response_code(200);
                echo json_encode($clients_arr);
            } else {
                http_response_code(200);
                echo json_encode(array("records" => array()));
            }
        } else {
            $stmt = $client->read();
            $num = $stmt->rowCount();
            
            if($num > 0) {
                $clients_arr = array();
                $clients_arr["records"] = array();
                
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    extract($row);
                    
                    // Fetch contact persons for this client
                    require_once __DIR__ . '/../models/ContactPerson.php';
                    $contactPerson = new ContactPerson($db);
                    $contactPerson->client_id = $id;
                    $contact_stmt = $contactPerson->read();
                    
                    $contact_persons = array();
                    while ($contact_row = $contact_stmt->fetch(PDO::FETCH_ASSOC)) {
                        $contact_persons[] = array(
                            "id" => $contact_row['id'],
                            "first_name" => $contact_row['first_name'],
                            "last_name" => $contact_row['last_name'],
                            "email" => $contact_row['email'],
                            "phone" => $contact_row['phone'],
                            "position" => $contact_row['position'],
                            "department" => $contact_row['department'],
                            "is_primary" => $contact_row['is_primary'],
                            "notes" => $contact_row['notes']
                        );
                    }
                    
                    $client_item = array(
                        "id" => $id,
                        "company_name" => $company_name,
                        "y_tunnus" => $y_tunnus,
                        "first_name" => $first_name,
                        "last_name" => $last_name,
                        "email" => $email,
                        "phone" => $phone,
                        "address" => $address,
                        "city" => $city,
                        "state" => $state,
                        "postal_code" => $postal_code,
                        "country" => $country,
                        "notes" => $notes,
                        "hour_price" => $hour_price,
                        "contact_persons" => $contact_persons,
                        "created_at" => $created_at,
                        "updated_at" => $updated_at
                    );
                    
                    array_push($clients_arr["records"], $client_item);
                }
                
                http_response_code(200);
                echo json_encode($clients_arr);
            } else {
                http_response_code(200);
                echo json_encode(array("records" => array()));
            }
        }
        break;
        
    case 'POST':
        $data = json_decode(file_get_contents("php://input"));
        
        if(!empty($data->first_name) && !empty($data->last_name) && !empty($data->email)) {
            $client->company_name = $data->company_name ?? '';
            $client->y_tunnus = $data->y_tunnus ?? '';
            $client->first_name = $data->first_name;
            $client->last_name = $data->last_name;
            $client->email = $data->email;
            $client->phone = $data->phone ?? '';
            $client->address = $data->address ?? '';
            $client->city = $data->city ?? '';
            $client->state = $data->state ?? '';
            $client->postal_code = $data->postal_code ?? '';
            $client->country = $data->country ?? '';
            $client->notes = $data->notes ?? '';
            $client->hour_price = $data->hour_price ?? 0;
            
            if($client->create()) {
                http_response_code(201);
                echo json_encode(array("message" => "Client was created."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to create client."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to create client. Data is incomplete."));
        }
        break;
        
    case 'PUT':
        $data = json_decode(file_get_contents("php://input"));
        
        if(!empty($data->id) && !empty($data->first_name) && !empty($data->last_name) && !empty($data->email)) {
            $client->id = $data->id;
            $client->company_name = $data->company_name ?? '';
            $client->y_tunnus = $data->y_tunnus ?? '';
            $client->first_name = $data->first_name;
            $client->last_name = $data->last_name;
            $client->email = $data->email;
            $client->phone = $data->phone ?? '';
            $client->address = $data->address ?? '';
            $client->city = $data->city ?? '';
            $client->state = $data->state ?? '';
            $client->postal_code = $data->postal_code ?? '';
            $client->country = $data->country ?? '';
            $client->notes = $data->notes ?? '';
            $client->hour_price = $data->hour_price ?? 0;
            
            if($client->update()) {
                http_response_code(200);
                echo json_encode(array("message" => "Client was updated."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to update client."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to update client. Data is incomplete."));
        }
        break;
        
    case 'DELETE':
        if(isset($_GET['id'])) {
            $client->id = $_GET['id'];
            
            if($client->delete()) {
                http_response_code(200);
                echo json_encode(array("message" => "Client was deleted."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to delete client."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to delete client. ID is missing."));
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Method not allowed."));
        break;
}
?>
