<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include 'connectdb.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    if (!isset($input['id'])) {
        echo json_encode(['success' => false, 'message' => 'Invalid request.']);
        exit();
    }

    $recordId = $input['id'];
    $connection = $DB_con;

    try {
        // Fetch the record to duplicate
        $stmt = $connection->prepare("SELECT * FROM account WHERE id = ?");
        $stmt->execute([$recordId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            echo json_encode(['success' => false, 'message' => 'Record not found.']);
            exit();
        }

        // Prepare and execute the duplicate record insertion
        $stmt = $connection->prepare("
            INSERT INTO account (fname, mname, lname, uname, upass, phone, email, type, reg_date, work, uname, addr, sex, dob, marry, t_bal, a_bal, currency, cot, tax, imf, pin_auth, tmp_otp, pin, verify)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,  ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $row['fname'], $row['mname'], $row['lname'], $row['uname'], $row['upass'], $row['phone'],
            $row['email'], $row['type'], $row['reg_date'], $row['work'], $row['uname'], $row['addr'],
            $row['sex'], $row['dob'], $row['marry'], $row['t_bal'], $row['a_bal'], $row['currency'],
            $row['cot'], $row['tax'], $row['imf'], $row['pin_auth'], $row['tmp_otp'], $row['pin'], $row['verify']
        ]);

        echo json_encode(['success' => true, 'message' => 'Record duplicated successfully.']);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
    }
}
?>
