<?php
// models/Detail_Pemesanan.php

require_once dirname(__DIR__) . '/models/BaseModel.php';

class Detail_Pemesanan extends BaseModel {
    protected $table = 'detail_pemesanan';

    public function __construct(mysqli $conn) {
        parent::__construct($conn);
    }

    public function createPemesanan($users_id, $jadwal_id, $kursi_id, $harga_saat_pemesanan, $status_pemesanan = 'pending', $metode_pembayaran = null) {
        $stmt_check = $this->conn->prepare(
            "SELECT COUNT(*) FROM {$this->table} WHERE jadwal_id = ? AND kursi_id = ? AND status_pemesanan IN ('pending', 'paid')"
        );
        
        if (!$stmt_check) {
            error_log("SQL Prepare (SELECT COUNT) FAILED in createPemesanan: " . $this->conn->error);
            return false;
        }

        $stmt_check->bind_param("ii", $jadwal_id, $kursi_id);
        $stmt_check->execute();
        $result_check = $stmt_check->get_result();
        $row = $result_check->fetch_row();
        
        if ($row[0] > 0) {
            error_log("Attempted to book already occupied or pending seat: Jadwal ID " . $jadwal_id . ", Kursi ID " . $kursi_id);
            return false;
        }

        $stmt = $this->conn->prepare(
            "INSERT INTO {$this->table} (users_id, jadwal_id, kursi_id, harga_saat_pemesanan, status_pemesanan, metode_pembayaran, tanggal_pemesanan) 
             VALUES (?, ?, ?, ?, ?, ?, NOW())"
        );
        
        if (!$stmt) {
            error_log("SQL Prepare (INSERT) FAILED in createPemesanan: " . $this->conn->error);
            return false;
        }

        $stmt->bind_param("iiidss", $users_id, $jadwal_id, $kursi_id, $harga_saat_pemesanan, $status_pemesanan, $metode_pembayaran);
        
        if ($stmt->execute()) {
            return true;
        } else {
            error_log("SQL INSERT FAILED in createPemesanan for Kursi ID " . $kursi_id . ". Error: " . $stmt->error); 
            return false;
        }
    }

    public function getPemesananByUser($user_id) {
        $sql = "SELECT dp.*, j.tanggal_tayang, j.waktu_tayang, j.harga_tiket,
                             f.judul AS film_judul, s.nama AS studio_nama, krs.nomor AS kursi_nomor
                FROM {$this->table} dp
                JOIN jadwal j ON dp.jadwal_id = j.id
                JOIN film f ON j.film_id = f.id
                JOIN studio s ON f.studio_id = s.id
                JOIN kursi krs ON dp.kursi_id = krs.id
                WHERE dp.users_id = ?
                ORDER BY dp.tanggal_pemesanan DESC";
        $stmt = $this->conn->prepare($sql);
        if (!$stmt) { error_log("Prepare failed in getPemesananByUser: " . $this->conn->error); return []; }
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $pemesanan = [];
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $pemesanan[] = $row;
            }
        }
        return $pemesanan;
    }

    public function getPemesananById($pemesanan_id) {
        $sql = "SELECT dp.*, j.tanggal_tayang, j.waktu_tayang, j.harga_tiket,
                             f.judul AS film_judul, s.nama AS studio_nama, krs.nomor AS kursi_nomor,
                             u.fullname AS user_fullname, u.username AS user_username, u.email AS user_email
                FROM {$this->table} dp
                JOIN jadwal j ON dp.jadwal_id = j.id
                JOIN film f ON j.film_id = f.id
                JOIN studio s ON f.studio_id = s.id
                JOIN kursi krs ON dp.kursi_id = krs.id
                JOIN users u ON dp.users_id = u.id
                WHERE dp.id = ?";
        $stmt = $this->conn->prepare($sql);
        if (!$stmt) { error_log("Prepare failed in getPemesananById: " . $this->conn->error); return null; }
        $stmt->bind_param("i", $pemesanan_id);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }

    public function updateStatusPemesanan($pemesanan_id, $status) {
        $stmt = $this->conn->prepare("UPDATE {$this->table} SET status_pemesanan = ? WHERE id = ?");
        if (!$stmt) { error_log("Prepare failed in updateStatusPemesanan: " . $this->conn->error); return false; }
        $stmt->bind_param("si", $status, $pemesanan_id);
        return $stmt->execute();
    }

    public function getPemesananCountByUser($user_id) {
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM {$this->table} WHERE users_id = ?");
        if (!$stmt) { error_log("Prepare failed in getPemesananCountByUser: " . $this->conn->error); return 0; }
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_row();
        return (int)$row[0];
    }

    public function getPemesananCountByJadwal(int $jadwal_id): int {
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM {$this->table} WHERE jadwal_id = ?");
        if (!$stmt) { error_log("Prepare failed in getPemesananCountByJadwal: " . $this->conn->error); return 0; }
        $stmt->bind_param("i", $jadwal_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_row();
        return (int)$row[0];
    }

    public function getAllPemesanan() {
        $sql = "SELECT dp.*, j.tanggal_tayang, j.waktu_tayang, j.harga_tiket,
                             f.judul AS film_judul, s.nama AS studio_nama, krs.nomor AS kursi_nomor,
                             u.fullname AS user_fullname, u.username AS user_username
                FROM {$this->table} dp
                JOIN jadwal j ON dp.jadwal_id = j.id
                JOIN film f ON j.film_id = f.id
                JOIN studio s ON f.studio_id = s.id
                JOIN kursi krs ON dp.kursi_id = krs.id
                JOIN users u ON dp.users_id = u.id
                ORDER BY dp.tanggal_pemesanan DESC";
        $result = $this->conn->query($sql);
        $pemesanan_list = [];
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $pemesanan_list[] = $row;
            }
        }
        return $pemesanan_list;
    }

    public function getPemesananCountByKursi($kursi_id) {
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM {$this->table} WHERE kursi_id = ?");
        if (!$stmt) { error_log("Prepare failed in getPemesananCountByKursi: " . $this->conn->error); return 0; }
        $stmt->bind_param("i", $kursi_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_row();
        return (int)$row[0];
    }

    public function deleteByJadwalId(int $jadwal_id): bool {
        $stmt = $this->conn->prepare("DELETE FROM {$this->table} WHERE jadwal_id = ?");
        if (!$stmt) {
            error_log("SQL Prepare (DELETE by Jadwal ID) FAILED in deleteByJadwalId: " . $this->conn->error);
            return false;
        }
        $stmt->bind_param("i", $jadwal_id);
        if ($stmt->execute()) {
            return true;
        } else {
            error_log("SQL Execute (DELETE by Jadwal ID) FAILED in deleteByJadwalId for jadwal_id {$jadwal_id}. Error: " . $stmt->error);
            return false;
        }
    }
}