<?php
// Database connection details
require 'dbconfig/dbconfig.php';

// initalize the form submission
$form_sucecss = false;

// if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $name = htmlspecialchars($_POST['name']);
    $idNo = htmlspecialchars($_POST['idNo']);
    $dob = htmlspecialchars($_POST['dob']);
    $contactNo = htmlspecialchars($_POST['contactNo']);
    $province = htmlspecialchars($_POST['province']);
    $district = htmlspecialchars($_POST['district']);

    $target_dir_page = "uploads/fbPage/";
    if (!is_dir($target_dir_page)) {
        mkdir($target_dir_page, 0777, true);
    }

    $target_dir_profile = "uploads/profile/";
    if (!is_dir($target_dir_profile)) {
        mkdir($target_dir_profile, 0777, true);
    }
    
    // Handle profile image upload
    $profile_image = $target_dir_profile . time() . basename($_FILES["images"]["name"]);
    if (!move_uploaded_file($_FILES["images"]["tmp_name"], $profile_image)) {
        $response = [
            'status' => 'error',
            'message' => 'Error uploading files.'
        ];
        echo json_encode($response);
        exit;
    }

    // Handle page screenshot upload
    $page_screenshot = $target_dir_page . time() . basename($_FILES["imagesPage"]["name"]);
    if (!move_uploaded_file($_FILES["imagesPage"]["tmp_name"], $page_screenshot)) {
        $response = [
            'status' => 'error',
            'message' => 'Error uploading page screenshot.'
        ];
        echo json_encode($response);
        exit;
    }

    // Insert data into the database
    $stmt = $conn->prepare("INSERT INTO users (name, id_no, dob, contact_no, province, district, profile_image, page_screenshot) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssss", $name, $idNo, $dob, $contactNo, $province, $district, $profile_image, $page_screenshot);

    if ($stmt->execute()) {
        $response = [
            'status' => 'success',
            'message' => 'Data inserted successfully.'
        ];
    } else {
        $response = [
            'status' => 'error',
            'message' => 'Error inserting data into the database.'
        ];
    }
    // Close statement
    $stmt->close();

    // Close connection
    $conn->close();

     // Return the response as JSON
     echo json_encode($response);
     exit;
}
?> 