<?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/Project.php';
require_once __DIR__ . '/../models/Subproject.php';

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

$project = new Project($db);
$subproject = new Subproject($db);

$request_method = $_SERVER['REQUEST_METHOD'];

switch($request_method) {
    case 'GET':
        if(isset($_GET['id'])) {
            $project->id = $_GET['id'];
            $project->readOne();
            
            if($project->project_name != null) {
                $project_arr = array(
                    "id" => $project->id,
                    "customer_id" => $project->customer_id,
                    "project_name" => $project->project_name,
                    "description" => $project->description,
                    "status" => $project->status,
                    "start_date" => $project->start_date,
                    "end_date" => $project->end_date,
                    "budget" => $project->budget,
                    "created_at" => $project->created_at,
                    "updated_at" => $project->updated_at,
                    "customer_name" => $company_name ? $company_name : ($first_name . ' ' . $last_name),
                    "status_badge" => $project->getStatusBadge(),
                    "progress" => $project->getProgress()
                );
                
                http_response_code(200);
                echo json_encode($project_arr);
            } else {
                http_response_code(404);
                echo json_encode(array("message" => "Project not found."));
            }
        } elseif(isset($_GET['customer_id'])) {
            $stmt = $project->read();
            $num = $stmt->rowCount();
            
            if($num > 0) {
                $projects_arr = array();
                $projects_arr["records"] = array();
                
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    extract($row);
                    
                    $project_item = array(
                        "id" => $id,
                        "customer_id" => $customer_id,
                        "project_name" => $project_name,
                        "description" => $description,
                        "status" => $status,
                        "start_date" => $start_date,
                        "end_date" => $end_date,
                        "budget" => $budget,
                        "created_at" => $created_at,
                        "updated_at" => $updated_at,
                        "customer_name" => $company_name ? $company_name : ($first_name . ' ' . $last_name),
                        "status_badge" => $project->getStatusBadge(),
                        "progress" => $project->getProgress()
                    );
                    
                    array_push($projects_arr["records"], $project_item);
                }
                
                http_response_code(200);
                echo json_encode($projects_arr);
            } else {
                http_response_code(200);
                echo json_encode(array("records" => array()));
            }
        } else {
            $stmt = $project->read();
            $num = $stmt->rowCount();
            
            if($num > 0) {
                $projects_arr = array();
                $projects_arr["records"] = array();
                
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    extract($row);
                    
                    $project_item = array(
                        "id" => $id,
                        "customer_id" => $customer_id,
                        "project_name" => $project_name,
                        "description" => $description,
                        "status" => $status,
                        "start_date" => $start_date,
                        "end_date" => $end_date,
                        "budget" => $budget,
                        "created_at" => $created_at,
                        "updated_at" => $updated_at,
                        "customer_name" => $company_name ? $company_name : ($first_name . ' ' . $last_name),
                        "status_badge" => $project->getStatusBadge(),
                        "progress" => $project->getProgress()
                    );
                    
                    array_push($projects_arr["records"], $project_item);
                }
                
                http_response_code(200);
                echo json_encode($projects_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->customer_id) && !empty($data->project_name)) {
            $project->customer_id = $data->customer_id;
            $project->project_name = $data->project_name;
            $project->description = $data->description ?? '';
            $project->status = $data->status ?? 'planning';
            $project->start_date = $data->start_date ?? null;
            $project->end_date = $data->end_date ?? null;
            $project->budget = $data->budget ?? null;
            
            if($project->create()) {
                http_response_code(201);
                echo json_encode(array("message" => "Project was created."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to create project."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to create project. Customer ID and project name are required."));
        }
        break;
        
    case 'PUT':
        $data = json_decode(file_get_contents("php://input"));
        $project_id = isset($_GET['id']) ? $_GET['id'] : '';
        
        if(!empty($project_id) && !empty($data->customer_id) && !empty($data->project_name)) {
            $project->id = $project_id;
            $project->customer_id = $data->customer_id;
            $project->project_name = $data->project_name;
            $project->description = $data->description ?? '';
            $project->status = $data->status ?? 'planning';
            $project->start_date = $data->start_date ?? null;
            $project->end_date = $data->end_date ?? null;
            $project->budget = $data->budget ?? null;
            
            if($project->update()) {
                http_response_code(200);
                echo json_encode(array("message" => "Project was updated."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to update project."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to update project. Data is incomplete."));
        }
        break;
        
    case 'DELETE':
        if(isset($_GET['id'])) {
            $project->id = $_GET['id'];
            
            if($project->delete()) {
                http_response_code(200);
                echo json_encode(array("message" => "Project was deleted."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to delete project."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to delete project. ID is missing."));
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Method not allowed."));
        break;
}
?>
