<?php
include('con.php');

$msg = '';

// Handle certificate upload
if (isset($_POST['upload_cert'])) {
    $id = intval($_POST['history_id']);
    $file = $_FILES['certificate']['name'];
    $upload_dir = "new/birth/";

    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    $file_path = $upload_dir . time() . "_" . basename($file);
    $allowed_types = ['jpg', 'jpeg', 'png', 'webp', 'pdf'];
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed_types)) {
        $msg = "Only JPG, JPEG, PNG, WEBP, and PDF files are allowed.";
    } else {
        if (move_uploaded_file($_FILES['certificate']['tmp_name'], $file_path)) {
            // ✅ Update cert path and set status=1 when upload successful
            mysqli_query($ahk_conn, "UPDATE new_service_history SET cert='$file_path', status=1 WHERE id='$id'");
            $msg = "Certificate uploaded successfully!";
        } else {
            $msg = "Error uploading file.";
        }
    }
}

// Handle status update
if (isset($_POST['update_status'])) {
    $id = intval($_POST['history_id']);
    $status = intval($_POST['status']);
    mysqli_query($ahk_conn, "UPDATE new_service_history SET status='$status' WHERE id='$id'");
    $msg = "Status updated successfully!";
}

// ✅ Fetch all rows
$result = mysqli_query($ahk_conn, "SELECT * FROM new_service_history ORDER BY id DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>New Service History</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>
<div class="container mt-5">
    <h4 class="text-center mb-4 text-primary">New Service History</h4>

    <?php if ($msg): ?>
    <script>
        Swal.fire({
            icon: 'info',
            title: 'Notice',
            text: <?php echo json_encode($msg); ?>
        });
    </script>
    <?php endif; ?>

    <table class="table table-bordered table-striped align-middle text-center">
        <thead class="table-dark">
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Aadhar</th>
                <th>Mobile</th>
                <th>State</th>
                <th>Date</th>
                <th>Status</th>
                <th>Certificate</th>
                <th>Upload Certificate</th>
                <th>Update Status</th>
            </tr>
        </thead>
        <tbody>
        <?php while ($row = mysqli_fetch_assoc($result)): ?>
            <tr>
                <td><?php echo $row['id']; ?></td>
                <td><?php echo htmlspecialchars($row['name']); ?></td>
                <td><?php echo htmlspecialchars($row['aadhar']); ?></td>
                <td><?php echo htmlspecialchars($row['mobile']); ?></td>
                <td><?php echo htmlspecialchars($row['state']); ?></td>
                <td><?php echo htmlspecialchars($row['date']); ?></td>
                <td>
                    <?php
                        $status_text = ['0'=>'Pending','1'=>'Inprocess','2'=>'Complete'];
                        echo isset($status_text[$row['status']]) ? $status_text[$row['status']] : 'Unknown';
                    ?>
                </td>
                <td>
                    <?php if ($row['cert']): ?>
                        <a href="<?php echo $row['cert']; ?>" target="_blank">View</a>
                    <?php else: ?>
                        N/A
                    <?php endif; ?>
                </td>
                <td>
                    <form method="POST" enctype="multipart/form-data">
                        <input type="file" name="certificate" accept="image/*,application/pdf" required class="form-control mb-1">
                        <input type="hidden" name="history_id" value="<?php echo $row['id']; ?>">
                        <button type="submit" name="upload_cert" class="btn btn-sm btn-success w-100">Upload</button>
                    </form>
                </td>
                <td>
                    <form method="POST">
                        <select name="status" class="form-select mb-1">
                            <option value="0" <?php echo ($row['status']==0)?'selected':''; ?>>Pending</option>
                            <option value="1" <?php echo ($row['status']==1)?'selected':''; ?>>Inprocess</option>
                            <option value="2" <?php echo ($row['status']==2)?'selected':''; ?>>Complete</option>
                        </select>
                        <input type="hidden" name="history_id" value="<?php echo $row['id']; ?>">
                        <button type="submit" name="update_status" class="btn btn-sm btn-primary w-100">Update</button>
                    </form>
                </td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
</div>
</body>
</html>
