<?php

ini_set('display_errors', 1);
ini_set('system_startup_errors',1);
error_reporting(E_ALL);

include 'includes/db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['deleteUser'])) {
    header('Content-Type: application/json');
    $userId = $_POST['id'];

    // Assuming you have established a PDO connection as $conn
    try {
        $query = "DELETE FROM users WHERE id = :id";
        $stmt = $conn->prepare($query);
        $stmt->bindParam(':id', $userId);

        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'message' => 'User deleted successfully.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to delete user.']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => 'Error: ' . $e->getMessage()]);
    }
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['createUser'])) {
header('Content-Type: application/json');
    
    // Collect the form data
    $fnam = $_POST['fname'];
    $lnam = $_POST['lname'];
    $mname = $_POST['mname'];
    $email = $_POST['email'];
    $password = $_POST['password']; // Hash the password
    $cpassword = $_POST['cpassword']; // Hash the password
    $status = $_POST['status'];
    $role = 'other';
    $phone = $_POST['phone'];
    $parent_position = $_POST['parent_position'];
    $current_position = $_POST['current_position'];
    $child_position = isset($_POST['child_position']) ? implode(',', $_POST['child_position']) : null;

    if($password !== $cpassword){
        echo json_encode(['status' => 'error', 'message' => "Confirm password dosen't match"]);
        exit;
    }

    // Handling the file upload
    $profilePic = null;
    // if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] == 0) {
    // $file_name = uniqid() . '_' . basename($_FILES["profile_pic"]["name"]); // Ensure unique file names
    // error_log(print_r($_FILES['profile_pic'], true));
    
    // $target_dir = "uploads/profile_pics/";
    // $target_file = $target_dir . $file_name;
    // $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // // Basic file validation
    // if ($_FILES["profile_pic"]["size"] > 2000000) {
    //     echo json_encode(['status' => 'error', 'message' => 'File size exceeds 2MB!']);
    //     exit;
    // } elseif (!in_array($imageFileType, ['jpg', 'jpeg', 'png'])) {
    //     echo json_encode(['status' => 'error', 'message' => 'Only JPG, JPEG, and PNG files are allowed!']);
    //     exit;
    // } else {
    //     // Move the uploaded file to the target directory
    //     if (move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $target_file)) {
    //         $profilePic = $file_name; // Save the file name for the database
    //         error_log("File successfully uploaded: " . $target_file);
    //     } else {
    //         error_log("Failed to move uploaded file.");
    //         echo json_encode(['status' => 'error', 'message' => 'Sorry, there was an error uploading your file.']);
    //         exit;
    //     }
    // }
    // } else {
    //     echo json_encode(['status' => 'error', 'message' => 'No file uploaded.']);
    //     exit;
    // }


    // Prepare the SQL insert statement, including profile_pic
    $sql = "INSERT INTO users (fname, lname, mname, email, password, status, role, phone, profile_pic, current_position, parent_position, child_position) 
            VALUES (:fnam, :lnam, :mname, :email, :password, :status, :role, :phone, :profile_pic, :current_position, :parent_position, :child_position)";

    try {
        // Prepare statement using PDO
        $stmt = $conn->prepare($sql);

        // Bind parameters
        $stmt->bindParam(':fnam', $fnam);
        $stmt->bindParam(':lnam', $lnam);
        $stmt->bindParam(':mname', $mname);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':password', $password); // Storing the hashed password
        $stmt->bindParam(':status', $status);
        $stmt->bindParam(':role', $role);
        $stmt->bindParam(':phone', $phone);
        $stmt->bindParam(':profile_pic', $profilePic); // Bind the file path to the profile_pic column
        $stmt->bindParam(':current_position', $current_position);
        $stmt->bindParam(':parent_position', $parent_position);
        $stmt->bindParam(':child_position', $child_position);

        // Execute the statement
        $stmt->execute();

        // Send success response
        echo json_encode([
            'status' => 'success',
            'message' => 'User added successfully!'
        ]);
    } catch (PDOException $e) {
        // Send error response
        echo json_encode([
            'status' => 'error',
            'message' => "Failed to add user. Please try again: " . $e->getMessage()
        ]);
    }
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['updateUser'])) {
    $userId = $_POST['userId']; // Get the user ID from the request
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $role = 'other';
    $status = $_POST['status'];
    $password = $_POST['password'];
    $parent_position = $_POST['parent_position'];
    $current_position = $_POST['current_position'];
    $child_position = isset($_POST['child_position']) ? implode(',', $_POST['child_position']) : null;

    // Perform validation (you can add your validation logic here)
    
    try {
        // Assuming $conn is your PDO connection
        $query = "UPDATE users SET fname = :fname, lname = :lname, email = :email, phone = :phone, role = :role, status = :status, password = :password, current_position = :current_position, parent_position = :parent_position, child_position = :child_position WHERE id = :userId";
        
        $stmt = $conn->prepare($query);
        $stmt->bindParam(':fname', $fname);
        $stmt->bindParam(':lname', $lname);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':phone', $phone);
        $stmt->bindParam(':role', $role);
        $stmt->bindParam(':status', $status);
        $stmt->bindParam(':password', $password);
        $stmt->bindParam(':current_position', $current_position);
        $stmt->bindParam(':parent_position', $parent_position);
        $stmt->bindParam(':child_position', $child_position);
        $stmt->bindParam(':userId', $userId);
        
        if ($stmt->execute()) {
            echo "<script>
                    alert('User updated successfully.');
                    window.location.href='users.php';
                  </script>";
            // echo json_encode(['status' => 'success', 'message' => 'User updated successfully.']);
        } else {
            echo "<script>
                    alert('Failed to update user.');
                    window.location.href='users.php';
                  </script>";
            // echo json_encode(['status' => 'error', 'message' => 'Failed to update user.']);
        }
    } catch (PDOException $e) {
        echo "<script>alert('Error: " . $e->getMessage() . "')</script>";
        // echo json_encode(['status' => 'error', 'message' => 'Error occurred: ' . $e->getMessage()]);
    }
}


?>
