<?php

require_once dirname(__DIR__) . '/models/Asset.php';
require_once dirname(__DIR__) . '/models/Maintenance.php';
require_once dirname(__DIR__) . '/../config/db.php';

class MaintenanceController {
    private $conn;

    public function __construct() {
        $this->conn = connectDB();
    }

    // Display asset details, maintenance history, and maintenance form
    public function index() {
        $this->showAssetDetail();
    }

    public function showAssetDetail() {
        if (!isset($_GET['id'])) {
            // Handle error, redirect or show message
            header("Location: ?page=home&error=asset_id_missing"); // Redirect to home with error
            exit();
        }

        $asset_id = $_GET['id'];

        // Fetch Asset Details
        $asset = new Asset($this->conn);
        $asset->id_aset = $asset_id;
        $asset_found = $asset->readOne();

        if (!$asset_found) {
            // Handle error
            header("Location: ?page=home&error=asset_not_found"); // Redirect to home with error
            exit();
        }
        
        // Fetch Maintenance History
        $maintenance = new Maintenance($this->conn);
        $stmt = $maintenance->readByAssetId($asset_id);
        $maintenance_history = $stmt->fetchAll(PDO::FETCH_ASSOC);

        require_once dirname(__DIR__) . '/../views/maintenance/detail.php';
    }

    public function showMaintenanceForm() {
        if (!isset($_GET['id_aset'])) {
            header("Location: ?page=home&error=asset_id_missing_for_form");
            exit();
        }

        $asset_id = $_GET['id_aset'];
        $asset = new Asset($this->conn);
        $asset->id_aset = $asset_id;
        $asset_found = $asset->readOne();

        if (!$asset_found) {
            header("Location: ?page=home&error=asset_not_found_for_form");
            exit();
        }

        // Pass asset data to the form view
        $asset_data = $asset; // Use the fetched asset object

        require_once dirname(__DIR__) . '/../views/maintenance/form.php';
    }

    // Process the creation of a new maintenance record
    public function processCreate() {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $maintenance = new Maintenance($this->conn);
            $asset = new Asset($this->conn);

            // Set maintenance property values from form
            $maintenance->id_aset = $_POST['id_aset'];
            $maintenance->tanggal_maintenance = $_POST['tanggal_maintenance'];
            $maintenance->tindakan = $_POST['tindakan'];
            $maintenance->catatan_teknisi = $_POST['catatan_teknisi'];
            $maintenance->nama_teknisi = $_POST['nama_teknisi'];
            
            $maintenance->asset_category_for_assessment = $_POST['asset_category'] ?? null;
            
            // Handle assessment data by encoding the submitted array
            if (isset($_POST['assessment']) && is_array($_POST['assessment'])) {
                $maintenance->assessment_data = json_encode($_POST['assessment']);
            } else {
                $maintenance->assessment_data = null;
            }

            // Set asset property values to update its status
            $asset->id_aset = $_POST['id_aset'];
            $asset->status_aset = $_POST['status_aset_baru'];

            // We need to fetch all asset data before updating, because our update method updates all fields.
            // This is a weakness of the current Asset->update() method, but we'll work with it for now.
            if ($asset->readOne()) {
                $asset->status_aset = $_POST['status_aset_baru']; // Overwrite status
                $asset->update(); // Update asset status
            }

            // Attempt to create the maintenance record
            if ($maintenance->create()) {
                header("Location: ?page=maintenance&id=" . htmlspecialchars($_POST['id_aset']) . "&message=maintenance_added");
                exit();
            } else {
                header("Location: ?page=maintenance_form&id_aset=" . htmlspecialchars($_POST['id_aset']) . "&error=add_failed");
                exit();
            }

        } else {
            header("Location: ?page=home&error=invalid_request");
            exit();
        }
    }

    public function showAllHistory() {
        $maintenance = new Maintenance($this->conn);
        $all_maintenance_history = $maintenance->readAllHistory()->fetchAll(PDO::FETCH_ASSOC);
        require_once dirname(__DIR__) . '/../views/maintenance/history.php';
    }
}
