<?php
session_start();
require_once 'config/db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION = $_POST; // เก็บค่าที่กรอกไว้ใน session เพื่อนำกลับไปแสดง

    // รับค่าจากฟอร์ม
    $Agency_Name = $_POST['Agency_Name'];
    $Tax_ID = $_POST['Tax_ID'];
    $Address = $_POST['Address'];
    $Address_Sent = $_POST['Address_Sent'] ?? '';
    $Address_Test = $_POST['Address_Test'];
    $Address_Eng = $_POST['Address_Eng'] ?? '';
    $Office_Number = $_POST['Office_Number'];
    $Web_Name = $_POST['Web_Name'];
    $On_Off_Agency = $_POST['On_Off_Agency'] ?? 'Off';
    $Edit_Agency = $_POST['Edit_Agency'] ?? 'Off';
    $New_Agency = 'On';

    $Customer_Name = $_POST['Customer_Name'];
    $Mobile_Number = $_POST['Mobile_Number'];
    $Email = $_POST['Email'];
    $Password = $_POST['Password'];
    $c_password = $_POST['c_password'];
    $Level = 'User';
    $On_Off_Customer = $_POST['On_Off_Customer'] ?? 'Off';
    $Edit_Customer = $_POST['Edit_Customer'] ?? 'Off';
    $New_Customer = 'On';

    // ตรวจสอบข้อมูล
    $errors = [];

    if (empty($Customer_Name)) $errors[] = 'กรุณากรอกชื่อผู้ใช้งาน';
    if (empty($Mobile_Number)) {
        $errors[] = 'กรุณากรอกเบอร์โทรศัพท์';
    } elseif (!preg_match('/^\d{10}$/', $Mobile_Number)) {
        $errors[] = 'เบอร์โทรศัพท์ต้องเป็นตัวเลข 10 หลัก';
    }

    if (empty($Email)) {
        $errors[] = 'กรุณากรอกอีเมล';
    } elseif (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'รูปแบบอีเมลไม่ถูกต้อง';
    }

    if (empty($Password)) $errors[] = 'กรุณากรอกรหัสผ่าน';
    if (empty($c_password)) $errors[] = 'กรุณายืนยันรหัสผ่าน';
    if ($Password !== $c_password) $errors[] = 'รหัสผ่านและการยืนยันไม่ตรงกัน';

    if (!empty($errors)) {
        $_SESSION['error'] = implode('<br>', $errors);
    } else {
        try {
            $conn->beginTransaction();

            // ตรวจสอบอีเมลซ้ำ
            $check_email = $conn->prepare("SELECT Email FROM customer WHERE Email = :Email");
            $check_email->bindParam(":Email", $Email);
            $check_email->execute();
            if ($check_email->fetch(PDO::FETCH_ASSOC)) {
                $_SESSION['warning'] = 'มีอีเมลนี้อยู่ในระบบแล้ว';
                $conn->rollBack();
            } else {
                // ตรวจสอบ Tax_ID
                $check_tax_id = $conn->prepare("SELECT Agency_ID FROM agency WHERE Tax_ID = :Tax_ID");
                $check_tax_id->bindParam(":Tax_ID", $Tax_ID);
                $check_tax_id->execute();
                $existing_agency = $check_tax_id->fetch(PDO::FETCH_ASSOC);

                if (!$existing_agency) {
                    $stmtAgency = $conn->prepare("INSERT INTO agency (Agency_Name, Tax_ID, Address, Address_Sent, Address_Test, Address_Eng, Office_Number, Web_Name, On_Off_Agency, Edit_Agency, New_Agency, DtmIns, DtmUdp) 
                        VALUES (:Agency_Name, :Tax_ID, :Address, :Address_Sent, :Address_Test, :Address_Eng, :Office_Number, :Web_Name, :On_Off_Agency, :Edit_Agency, :New_Agency, NOW(), NOW())");
                    $stmtAgency->execute([
                        ':Agency_Name' => $Agency_Name,
                        ':Tax_ID' => $Tax_ID,
                        ':Address' => $Address,
                        ':Address_Sent' => $Address_Sent,
                        ':Address_Test' => $Address_Test,
                        ':Address_Eng' => $Address_Eng,
                        ':Office_Number' => $Office_Number,
                        ':Web_Name' => $Web_Name,
                        ':On_Off_Agency' => $On_Off_Agency,
                        ':Edit_Agency' => $Edit_Agency,
                        ':New_Agency' => $New_Agency
                    ]);
                    $Agency_ID = $conn->lastInsertId();
                } else {
                    $Agency_ID = $existing_agency['Agency_ID'];
                }

                // Insert customer
                $stmtMaxCustomerID = $conn->prepare("SELECT COALESCE(MAX(Customer_ID), 0) + 1 FROM customer");
                $stmtMaxCustomerID->execute();
                $Customer_ID = $stmtMaxCustomerID->fetchColumn();
                $passwordHash = password_hash($Password, PASSWORD_DEFAULT);

                $stmtCustomer = $conn->prepare("INSERT INTO customer (Customer_ID, Customer_Name, Mobile_Number, Email, Password, Level, On_Off_Customer, Edit_Customer, New_Customer, CusIns_ID, CusUdp_ID, DtmIns, DtmUdp) 
                    VALUES (:Customer_ID, :Customer_Name, :Mobile_Number, :Email, :Password, :Level, :On_Off_Customer, :Edit_Customer, :New_Customer, :CusIns_ID, :CusUdp_ID, NOW(), NOW())");
                $stmtCustomer->execute([
                    ':Customer_ID' => $Customer_ID,
                    ':Customer_Name' => $Customer_Name,
                    ':Mobile_Number' => $Mobile_Number,
                    ':Email' => $Email,
                    ':Password' => $passwordHash,
                    ':Level' => $Level,
                    ':On_Off_Customer' => $On_Off_Customer,
                    ':Edit_Customer' => $Edit_Customer,
                    ':New_Customer' => $New_Customer,
                    ':CusIns_ID' => $Customer_ID,
                    ':CusUdp_ID' => $Customer_ID
                ]);

                $stmtAgency_Customer = $conn->prepare("INSERT INTO agency_customer (Customer_ID, Agency_ID) VALUES (:Customer_ID, :Agency_ID)");
                $stmtAgency_Customer->execute([
                    ':Customer_ID' => $Customer_ID,
                    ':Agency_ID' => $Agency_ID
                ]);

                $conn->commit();
                $_SESSION['success'] = 'ลงทะเบียนเสร็จสิ้น';

                // ล้างข้อมูล
                unset($_SESSION['Agency_Name'], $_SESSION['Tax_ID'], $_SESSION['Address'], $_SESSION['Address_Sent'], $_SESSION['Address_Test'], $_SESSION['Address_Eng'],
                    $_SESSION['Office_Number'], $_SESSION['Web_Name'], $_SESSION['On_Off_Agency'], $_SESSION['Edit_Agency'], $_SESSION['Customer_Name'],
                    $_SESSION['Mobile_Number'], $_SESSION['Email'], $_SESSION['Password'], $_SESSION['c_password'], $_SESSION['On_Off_Customer'], $_SESSION['Edit_Customer']);
            }
        } catch (PDOException $e) {
            $conn->rollBack();
            $_SESSION['error'] = "เกิดข้อผิดพลาด: " . $e->getMessage();
        }
    }

    header("Location: registerForm.php");
    exit();
}
?>