<?php
session_start();
include '../../connection.php';

// Ensure user is logged in
if (!isset($_SESSION['user_id'])) {
    exit('Unauthorized access.');
}

// Validate and sanitize `page` parameter
if (!isset($_GET['page']) || empty($_GET['page'])) {
    exit('Invalid request.');
}

$id = htmlspecialchars($_GET['page']);
$year = date("y");

// Use prepared statements to prevent SQL injection
$stmt = $conn->prepare("
   SELECT 
    t.UniqueID,
    t.resident_id,
    t.description,
    t.status,
    t.date_created,
    t.supported_evidence,
    r.first_name,
    r.middle_name,
    r.last_name,
    c.complain_name,
    a.assignment_id,
    a.assigned_person,
    a.department_id,
    a.status AS assigned_status,
    a.deadline,
    a.date_created AS assigned_date,
    u.first_name AS user_fname,
    u.middle_name AS user_mname,
    u.last_name AS user_lname,
    u.contact AS user_contact,
    d.department_name,
    s.settle_date
FROM tbl_transaction AS t
LEFT JOIN tbl_resident AS r ON t.resident_id = r.resident_id
LEFT JOIN tbl_complaint_types AS c ON t.complaint_type_id = c.complaint_type_id
LEFT JOIN tbl_assignment AS a ON a.UniqueID = t.UniqueID
LEFT JOIN tbl_user AS u ON a.assigned_person = u.user_id
LEFT JOIN tbl_department AS d ON a.department_id = d.department_id
LEFT JOIN tbl_transaction_schedule AS s ON s.UniqueID = t.UniqueID
    WHERE t.UniqueID = ?
");

$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if (!$row) {
    exit('<div class="alert alert-danger">Complaint not found.</div>');
}
?>

<div class="container">
    <?php
    // Fetch user position
    $userid = $_SESSION['user_id'];
    $stmt_pos = $conn->prepare("SELECT position FROM tbl_organizational_structure WHERE user_id = ?");
    $stmt_pos->bind_param("i", $userid);
    $stmt_pos->execute();
    $pos_result = $stmt_pos->get_result();

    if ($pos_result && $pos_result->num_rows > 0) {
        $data = $pos_result->fetch_assoc();
        $position = strtoupper($data['position']);

        // Determine back page
        $backPage = ($position === 'SECRETARY')
            ? 'transactions.php'
            : 'assigned_complaint_kagawad.php';
    } else {
        $backPage = 'transactions.php';
    }
    ?>

    <!-- Back Button -->
    <button class="btn btn-secondary mb-3 btn-md click_page" data-page="<?= htmlspecialchars($backPage) ?>">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <div class="row">
        <!-- Main Complaint Information -->
        <div class="col-lg-8">
            <!-- Basic Information -->
            <div class="card complaint-card">
                <div class="card-header">
                    <i class="fas fa-info-circle mr-2"></i> Basic Information
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="detail-item">
                                <h6><i class="fas fa-hashtag text-primary mr-2"></i>Case Number</h6>
                                <p><?= htmlspecialchars($row['UniqueID']) ?> - <?= $year ?></p>
                            </div>
                            <div class="detail-item">
                                <h6><i class="fas fa-calendar-alt text-primary mr-2"></i>Date Filed</h6>
                                <p><?= date('F d, Y', strtotime($row['date_created'])) ?></p>
                            </div>
                            <div class="detail-item">
                                <h6><i class="fas fa-gavel text-primary mr-2"></i>Nature of Case</h6>
                                <p><?= htmlspecialchars($row['complain_name']) ?></p>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="detail-item">
                                <h6><i class="fas fa-user text-primary mr-2"></i>Assigned Officer</h6>
                                <p><?= htmlspecialchars(trim($row['user_fname'] . ' ' . $row['user_mname'] . ' ' . $row['user_lname'])) ?></p>
                                <p><i class="fas fa-phone mr-2"></i><?= htmlspecialchars($row['user_contact']) ?></p>
                            </div>
                            <div class="detail-item">
                                <h6><i class="fas fa-building text-primary mr-2"></i>Department</h6>
                                <p><?= htmlspecialchars($row['department_name']) ?></p>
                            </div>
                            <div class="detail-item">
                                <h6><i class="fas fa-flag text-primary mr-2"></i>Status</h6>
                                <p>
                                    <span class="badge 
                                        <?php 
                                            if ($row['status'] === 'new') echo 'status-new';
                                            elseif ($row['status'] === 'in-progress') echo 'status-in-progress';
                                            elseif ($row['status'] === 'resolved') echo 'status-resolved';
                                            else echo 'status-default';
                                        ?>">
                                        <?= ucfirst($row['status']) ?>
                                    </span>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Case Details -->
            <div class="card complaint-card">
                <div class="card-header">
                    <i class="fas fa-clipboard-list mr-2"></i> Case Details
                </div>
                <div class="card-body">
                    <?php
                    $file = $row['supported_evidence'];
                    $path = "../uploads/evidence/" . htmlspecialchars($file);
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));

                    $image_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                    $video_ext = ['mp4', 'mov', 'avi', 'mkv', 'webm'];

                    if (in_array($ext, $image_ext)): ?>
                        <div class="detail-item">
                            <h6>Supporting Evidence (Image)</h6>
                            <img src="<?= $path ?>" alt="Evidence Image" class="img-fluid rounded shadow-sm" style="max-height:300px; object-fit:contain;">
                        </div>

                    <?php elseif (in_array($ext, $video_ext)): ?>
                        <div class="detail-item">
                            <p><strong>Description:</strong> <?= htmlspecialchars($row['description']) ?></p>
                            <h6>Supporting Evidence (Video)</h6>
                            <video controls class="w-100 rounded shadow-sm" style="max-height:350px;">
                                <source src="<?= $path ?>" type="video/<?= htmlspecialchars($ext) ?>">
                                Your browser does not support the video tag.
                            </video>
                        </div>

                    <?php elseif (!empty($file)): ?>
                        <div class="detail-item">
                            <h6>Supporting Evidence</h6>
                            <a href="<?= $path ?>" target="_blank" class="btn btn-outline-primary btn-sm">
                                View Evidence
                            </a>
                        </div>
                    <?php else: ?>
                        <p class="text-muted">No supporting evidence provided.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <div class="card complaint-card">
                <div class="card-header">
                    <i class="fas fa-history mr-2"></i> Case Timeline
                </div>
                <div class="card-body">
                    <div class="timeline">
                        <div class="timeline-item">
                            <h6>Complaint Filed</h6>
                            <p class="text-muted small"><?= date('F d, Y', strtotime($row['date_created'])) ?></p>
                            <p>Complaint submitted by <?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) ?></p>
                        </div>

                        <?php if (!empty($row['assigned_date'])): ?>
                        <div class="timeline-item">
                            <h6>Case Assigned</h6>
                            <p class="text-muted small"><?= date('F d, Y', strtotime($row['assigned_date'])) ?></p>
                            <p>Assigned to <?= htmlspecialchars($row['user_fname'] . ' ' . $row['user_lname']) ?></p>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($row['deadline'])): ?>
                        <div class="timeline-item">
                            <h6>Deadline</h6>
                            <p class="text-muted small"><?= date('F d, Y', strtotime($row['deadline'])) ?></p>
                            <p>Expected resolution date.</p>
                            <p class="text-muted small"><?= date('F d, Y', strtotime($row['settle_date'])) ?></p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Print Button -->
<button class="btn btn-primary print-btn" onclick="window.print()">
    <i class="fas fa-print fa-lg"></i> Print
</button>
