<?php
// pages/issue_form.php
requireRole('any');

$id = isset($_GET['id']) ? (int)$_GET['id'] : null;
$issue = null;
$error = null;
$success = null;

if ($id) {
    $stmt = $pdo->prepare("SELECT * FROM issues WHERE id = ?");
    $stmt->execute([$id]);
    $issue = $stmt->fetch();
}

// Auto-Repair Issue Table Schema for V2
try {
    $checkCols = $pdo->query("SHOW COLUMNS FROM issues")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('description_summary', $checkCols)) {
        $pdo->exec("ALTER TABLE `issues` ADD COLUMN `description_summary` VARCHAR(255) DEFAULT NULL AFTER `description` ");
    }
    if (!in_array('date_reported', $checkCols)) {
        $pdo->exec("ALTER TABLE `issues` ADD COLUMN `date_reported` DATETIME DEFAULT CURRENT_TIMESTAMP AFTER `resolution_notes` ");
        $pdo->exec("UPDATE issues SET date_reported = created_at WHERE date_reported IS NULL");
    }
} catch (Exception $e) { /* Fail silently */ }

// Fetch Members for Dropdowns
$members = $pdo->query("SELECT id, full_name FROM members WHERE status='Available' ORDER BY full_name ASC")->fetchAll();

// Fetch Settings Options
$issue_types = $pdo->query("SELECT value FROM settings_options WHERE category='issue_types' AND is_active=1 ORDER BY display_order")->fetchAll(PDO::FETCH_COLUMN);
$departments = $pdo->query("SELECT value FROM settings_options WHERE category='departments' AND is_active=1 ORDER BY display_order")->fetchAll(PDO::FETCH_COLUMN);
$units = $pdo->query("SELECT value FROM settings_options WHERE category='units' AND is_active=1 ORDER BY display_order")->fetchAll(PDO::FETCH_COLUMN);
$locations = $pdo->query("SELECT value FROM settings_options WHERE category='locations' AND is_active=1 ORDER BY display_order")->fetchAll(PDO::FETCH_COLUMN);

// Fetch Services for Dropdown (Recent 50)
$services_list = $pdo->query("SELECT id, type, service_date FROM services ORDER BY service_date DESC LIMIT 50")->fetchAll();

$status_options = ['Open', 'In Progress', 'Resolved', 'Closed'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = clean_input($_POST['type']);
    $priority = clean_input($_POST['priority']);
    $department = clean_input($_POST['department']);
    $unit = clean_input($_POST['unit']);
    $location = clean_input($_POST['location']);
    $description = clean_input($_POST['description']);
    $description_summary = clean_input($_POST['description_summary']);
    $date_reported = !empty($_POST['date_reported']) ? $_POST['date_reported'] : date('Y-m-d H:i:s');
    $reported_by = (int)$_POST['reported_by'];
    $assigned_to = !empty($_POST['assigned_to']) ? (int)$_POST['assigned_to'] : null;
    $resolution = isset($_POST['resolution_notes']) ? clean_input($_POST['resolution_notes']) : null;
    $status = isset($_POST['status']) ? $_POST['status'] : ($issue ? $issue['status'] : 'Open'); // Default to Open for new issues
    $service_id = !empty($_POST['service_id']) ? (int)$_POST['service_id'] : null;
    
    if (empty($description)) {
        $error = "Description is required";
    } else {
        if ($id) {
            // Update
            $sql = "UPDATE issues SET type=?, priority=?, department=?, unit=?, location=?, description=?, description_summary=?, date_reported=?, reported_by=?, assigned_to=?, resolution_notes=?, status=?, service_id=?, updated_at=NOW() WHERE id=?";
            $stmt = $pdo->prepare($sql);
            if ($stmt->execute([$type, $priority, $department, $unit, $location, $description, $description_summary, $date_reported, $reported_by, $assigned_to, $resolution, $status, $service_id, $id])) {
                $success = "Issue updated.";
                // Refresh
                 $stmt = $pdo->prepare("SELECT * FROM issues WHERE id = ?");
                 $stmt->execute([$id]);
                 $issue = $stmt->fetch();
            } else {
                $error = "Failed to update.";
            }
        } else {
            // Insert
            $sql = "INSERT INTO issues (type, priority, department, unit, location, description, description_summary, date_reported, reported_by, assigned_to, status, service_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'In Progress', ?)";
            $stmt = $pdo->prepare($sql);
            if ($stmt->execute([$type, $priority, $department, $unit, $location, $description, $description_summary, $date_reported, $reported_by, $assigned_to, $service_id])) {
                $success = "Issue reported successfully.";
                $id = $pdo->lastInsertId();
                 $stmt = $pdo->prepare("SELECT * FROM issues WHERE id = ?");
                 $stmt->execute([$id]);
                 $issue = $stmt->fetch();
            } else {
                $error = "Failed to report issue.";
            }
        }
    }
}
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <h1><?php echo $id ? 'Edit Issue' : 'Report Issue'; ?></h1>
    <a href="index.php?page=issues" class="btn" style="background-color: #666;">&laquo; Back to Issues</a>
</div>

<?php if ($error): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card">
    <form method="POST">
        <div class="dashboard-grid">
            <div style="grid-column: span 1;">
                <div class="form-group">
                    <label>Report Type *</label>
                    <select name="type" class="form-control" required>
                        <option value="">-- Select Type --</option>
                        <?php foreach($issue_types as $t): ?>
                        <option value="<?php echo htmlspecialchars($t); ?>" <?php if($issue && $issue['type']==$t) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($t); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Priority *</label>
                    <select name="priority" class="form-control" required>
                        <option value="normal" <?php if(!$issue || $issue['priority']=='normal') echo 'selected'; ?>>
                            🟡 Normal
                        </option>
                        <option value="urgent" <?php if($issue && $issue['priority']=='urgent') echo 'selected'; ?>>
                            🔴 Urgent
                        </option>
                        <option value="low" <?php if($issue && $issue['priority']=='low') echo 'selected'; ?>>
                            🟢 Low
                        </option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Department *</label>
                    <select name="department" class="form-control" required>
                        <option value="">-- Select Department --</option>
                        <?php foreach($departments as $d): ?>
                        <option value="<?php echo htmlspecialchars($d); ?>" <?php if($issue && $issue['department']==$d) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($d); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Unit</label>
                    <select name="unit" class="form-control">
                        <option value="">-- Select Unit --</option>
                        <?php foreach($units as $u): ?>
                        <option value="<?php echo htmlspecialchars($u); ?>" <?php if($issue && $issue['unit']==$u) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($u); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Location</label>
                    <select name="location" class="form-control">
                        <option value="">-- Select Location --</option>
                        <?php foreach($locations as $loc): ?>
                        <option value="<?php echo htmlspecialchars($loc); ?>" <?php if($issue && $issue['location']==$loc) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($loc); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Date & Time Reported *</label>
                    <input type="datetime-local" name="date_reported" class="form-control" required value="<?php echo ($issue && !empty($issue['date_reported'])) ? date('Y-m-d\TH:i', strtotime($issue['date_reported'])) : date('Y-m-d\TH:i'); ?>">
                </div>

                <div class="form-group">
                    <label>Reported By *</label>
                    <select name="reported_by" class="form-control" required>
                        <?php foreach($members as $m): ?>
                        <option value="<?php echo $m['id']; ?>" <?php if(($issue && $issue['reported_by'] == $m['id']) || (!$issue && isset($_SESSION['member_id']) && $_SESSION['member_id'] == $m['id'])) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($m['full_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Related Service</label>
                    <select name="service_id" class="form-control">
                        <option value="">-- No Specific Service --</option>
                        <?php foreach($services_list as $s): ?>
                        <option value="<?php echo $s['id']; ?>" <?php if($issue && $issue['service_id'] == $s['id']) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($s['type'] ?? '') . " (" . date('M j, Y', strtotime($s['service_date'] ?? 'now')) . ")"; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <div style="grid-column: span 1;">
                <div class="form-group">
                    <label>Description of Issue (Full Details) *</label>
                    <textarea name="description" class="form-control" rows="5" required><?php echo $issue ? htmlspecialchars($issue['description']) : ''; ?></textarea>
                </div>
                
                <div class="form-group">
                    <label>Summary of Issue (For Dashboard/Reports) *</label>
                    <input type="text" name="description_summary" class="form-control" maxlength="255" required value="<?php echo ($issue && isset($issue['description_summary'])) ? htmlspecialchars($issue['description_summary']) : ''; ?>" placeholder="Brief 1-line summary">
                </div>
                
                <div class="form-group">
                    <label>Assigned To</label>
                    <select name="assigned_to" class="form-control">
                        <option value="">-- Unassigned --</option>
                        <?php foreach($members as $m): ?>
                        <option value="<?php echo $m['id']; ?>" <?php if($issue && $issue['assigned_to'] == $m['id']) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($m['full_name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <?php if($issue): ?>
                <div class="form-group">
                    <label>Status</label>
                    <select name="status" class="form-control">
                        <option value="In Progress" <?php if($issue['status']=='In Progress') echo 'selected'; ?>>In Progress</option>
                        <option value="Resolved" <?php if($issue['status']=='Resolved') echo 'selected'; ?>>Resolved</option>
                        <option value="Closed" <?php if($issue['status']=='Closed') echo 'selected'; ?>>Closed</option>
                        <option value="Open" <?php if($issue['status']=='Open') echo 'selected'; ?>>Open</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Resolution Notes</label>
                    <textarea name="resolution_notes" class="form-control"><?php echo isset($issue['resolution_notes']) ? htmlspecialchars($issue['resolution_notes']) : ''; ?></textarea>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <div style="margin-top: 20px;">
            <button type="submit" class="btn btn-block"><?php echo $id ? 'Update Issue' : 'Submit Report'; ?></button>
        </div>
    </form>
</div>
