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

date_default_timezone_set('Asia/Kuala_Lumpur');
$currentDate = date('Y-m-d');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['users'])) {
    if (is_array($_POST['users'])) {
        
        $womenCount = 0;
        foreach ($_POST['users'] as $ic => $user) {
            if ($user['gender'] == 2) {
                $womenCount++;
            }
        }

        if ($womenCount < 2) {
            // Return JSON response for AJAX handling
            header('Content-Type: application/json');
            echo json_encode([
                'status' => 'error',
                'message' => 'PERLUKAN SEKURANG-KURANGNYA 2 CALON WANITA'
            ]);
            exit();
        }

        try {
            $conn->beginTransaction();
            $booking_id = null;

            foreach ($_POST['users'] as $ic => $user) {
                $name = $user['name'];
                $gender = $user['gender'];
                $masjid_id = $user['masjid_id'];
                $phone = $user['phone'];
                $address = $user['address'];
                $job = $user['job'];
                $booking_id = $user['booking_id'];
                $totalVote = intval($user['total_vote']);
                $status = 1;
            
                $stmt = $conn->prepare("
                    SELECT total_vote FROM form WHERE ic = :ic AND DATE(date) = :currentDate
                ");
                $stmt->bindParam(':ic', $ic, PDO::PARAM_STR);
                $stmt->bindParam(':currentDate', $currentDate, PDO::PARAM_STR);
                $stmt->execute();
                $existingRecord = $stmt->fetch(PDO::FETCH_ASSOC);
            
                if ($existingRecord) {
                    $updatedVote = $totalVote;
                    $stmt = $conn->prepare("
                        UPDATE form 
                        SET total_vote = :total_vote, status_code = :status_code
                        WHERE ic = :ic AND DATE(date) = :currentDate
                    ");
                    $stmt->bindParam(':total_vote', $updatedVote, PDO::PARAM_INT);
                    $stmt->bindParam(':status_code', $status, PDO::PARAM_INT);
                    $stmt->bindParam(':ic', $ic, PDO::PARAM_STR);
                    $stmt->bindParam(':currentDate', $currentDate, PDO::PARAM_STR);
                    $stmt->execute();
                } else {
                    $stmt = $conn->prepare("
                        INSERT INTO form (masjid_id, ic, name, gender, date, phone_num, address, job, total_vote, status_code, booking_id)
                        VALUES (:masjid_id, :ic, :name, :gender, NOW(), :phone, :address, :job, :total_vote, :status_code, :booking_id)
                    ");
                    $stmt->bindParam(':masjid_id', $masjid_id, PDO::PARAM_STR);
                    $stmt->bindParam(':ic', $ic, PDO::PARAM_STR);
                    $stmt->bindParam(':name', $name, PDO::PARAM_STR);
                    $stmt->bindParam(':gender', $gender, PDO::PARAM_STR);
                    $stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
                    $stmt->bindParam(':address', $address, PDO::PARAM_STR);
                    $stmt->bindParam(':job', $job, PDO::PARAM_STR);
                    $stmt->bindParam(':total_vote', $totalVote, PDO::PARAM_INT);
                    $stmt->bindParam(':status_code', $status, PDO::PARAM_INT);
                    $stmt->bindParam(':booking_id', $booking_id, PDO::PARAM_STR);
                    $stmt->execute();
                }
            }

            $conn->commit();
            $_SESSION['search_results'] = [];
            
            // Return JSON response for successful submission
            header('Content-Type: application/json');
            echo json_encode([
                'status' => 'success',
                'redirect' => 'form2_masjid.php?booking_id=' . $booking_id
            ]);
            exit();
            
        } catch (PDOException $e) {
            $conn->rollBack();
            header('Content-Type: application/json');
            echo json_encode([
                'status' => 'error',
                'message' => 'Error: ' . $e->getMessage()
            ]);
            exit();
        }
    } else {
        header('Content-Type: application/json');
        echo json_encode([
            'status' => 'error',
            'message' => 'Tiada data diterima!'
        ]);
        exit();
    }
}
?>