<?php 
include '../../connection.php';

if (isset($_POST['loading_emergency_total'])) {
   
   $query = "select count(*) total_emergency from tbl_emergency where emergency_status = 'Pending'";
   $query_result = $conn->query($query);

   if ($query_result) {
       $row = $query_result->fetch_assoc();
   $total = $row['total_emergency'];
   echo  $total;
   }
   
}

if (isset($_POST['update_status'])) {
    $emergency_id = intval($_POST['emergency_id']);
    $new_status = $conn->real_escape_string($_POST['emergency_status']);

    $query = "UPDATE tbl_emergency SET emergency_status = '$new_status' WHERE emergency_id = '$emergency_id'";
    if ($conn->query($query)) {
        echo "success";
    } else {
        http_response_code(500);
        echo "Database error: " . $conn->error;
    }
}

if (isset($_POST['loading_emergency'])) {
    $status = $_POST['status'] ?? '';


$query = "
    SELECT 
        e.emergency_id,
        e.resident_id,
        e.lattitude,
        e.longitude,
        e.emergency_status,
        e.date_created,
        e.description,
        r.first_name,
        r.middle_name,
        r.last_name,
        r.contact
    FROM tbl_emergency e
    LEFT JOIN tbl_resident r ON e.resident_id = r.resident_id
    " . ($status !== "" ? "WHERE e.emergency_status = '".$conn->real_escape_string($status)."'" : "") . "
    ORDER BY e.emergency_id DESC";

   
    $query_result = $conn->query($query);

    foreach ($query_result as $row) {

        // ✅ Full Name
        $fullname = $row['last_name'] . ', ' . $row['first_name'] . ' ' . $row['middle_name'];

        // ✅ Format timestamp (Today / Yesterday / Full Date)
        $timestamp = strtotime($row['date_created']);
        $today = date('Y-m-d');
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $dateOnly = date('Y-m-d', $timestamp);

        if ($dateOnly == $today) {
            $datetoday = "Today " . date('h:i A', $timestamp);
        } elseif ($dateOnly == $yesterday) {
            $datetoday = "Yesterday " . date('h:i A', $timestamp);
        } else {
            $datetoday = date('F d, Y h:i A', $timestamp);
        }

switch ($row['emergency_status']) {
    case 'Pending':
        $badgeClass = 'badge-warning';
        break;

    case 'Responding':
        $badgeClass = 'badge-info';
        break;

    case 'Resolved':
        $badgeClass = 'badge-success';
        break;

    default:
        $badgeClass = 'badge-secondary';
        break;
}
        // ✅ Generate card
        echo '
        <div class="card emergency-card priority-high" data-type="medical" data-priority="high">
            <div class="emergency-card-header">
                <h5 class="mb-0 text-danger"> Emergency Alert</h5>

                <div class="emergency-actions mt-3 d-flex gap-2">
              <div class="dropdown">
                <button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false">
                  Update Status
                </button>
                <div class="dropdown-menu">
                  <a class="dropdown-item update-status" 
                     data-id="' . $row['emergency_id'] . '" 
                     data-status="Pending">Pending</a>
                  <a class="dropdown-item update-status" 
                     data-id="' . $row['emergency_id'] . '" 
                     data-status="Responding">Responding</a>
                  <a class="dropdown-item update-status" 
                     data-id="' . $row['emergency_id'] . '" 
                     data-status="Resolved">Resolved</a>
                </div>
              </div>
            </div>
            </div>

            <div class="emergency-card-body">
                <div class="resident-info">
                    <img src="https://ui-avatars.com/api/?name=' . urlencode($fullname) . '&background=e74c3c&color=fff" class="resident-avatar">
                    <div class="resident-details">
                        <h5>' . htmlspecialchars($fullname) . '</h5>
                        <p><i class="fas fa-map-marker-alt mr-1"></i>  Location: <strong>(' . $row['lattitude'] . ', ' . $row['longitude'] . ')</strong></p>
                        <p><i class="fas fa-phone mr-1"></i>  +63 ' . htmlspecialchars($row['contact']) . '</p>
                    </div>
                </div>

                <div class="emergency-details">
              
                    <p><strong>Description:</strong> '.$row['description'].'.</p>
                    <p><strong>Time Reported:</strong> ' . $datetoday . '</p>
                    <p><strong>Status:</strong> <span class="badge '.$badgeClass.' text-uppercase">' . htmlspecialchars($row['emergency_status']) . '</span></p>
                </div>
                
                <!-- Mini Map -->
                <div class="map-container">
                    <div class="map-placeholder text-center">
                        <i class="fas fa-map-marker-alt fa-2x mb-2"></i>
                        <p> Latitude: ' . $row['lattitude'] . '<br> Longitude: ' . $row['longitude'] . '</p>
                        <button class="btn btn-sm btn-light view-full-map" 
                            data-lat="' . $row['lattitude'] . '" 
                            data-lng="' . $row['longitude'] . '" 
                            data-name="' . htmlspecialchars($fullname) . '">View Full Map</button>
                    </div>
                </div>


            </div>
        </div>';
    }
}

?>