<?php
include 'db.php';

$id = $_POST['id'];
$branch_code = $_POST['branch_code'];
$phone = $_POST['branch_phone'];
$province = $_POST['province'];
$ntn = $_POST['ntn'];
$strn = $_POST['strn'];
$branch_type = $_POST['branch_type'];
$is_active = isset($_POST['is_active']) ? 1 : 0;
$is_default = isset($_POST['is_default']) ? 1 : 0;

// If setting as default, remove default from other branches
if ($is_default) {
    $conn->query("UPDATE branch_info SET is_default = 0 WHERE id != $id");
}

$stmt = $conn->prepare("UPDATE branch_info SET branch_code = ?, branch_phone = ?, province = ?, ntn = ?, strn = ?, branch_type = ?, is_active = ?, is_default = ? WHERE id = ?");
$stmt->bind_param("ssssssiii", $branch_code, $phone, $province, $ntn, $strn, $branch_type, $is_active, $is_default, $id);
$stmt->execute();

// Handle logo upload
if (isset(
    $_FILES['branch_logo']) &&
    $_FILES['branch_logo']['error'] === UPLOAD_ERR_OK
) {
    $allowed_types = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'];
    $file_type = mime_content_type($_FILES['branch_logo']['tmp_name']);
    if (in_array($file_type, $allowed_types)) {
        $target_path = 'assets/img/branch_logo.png';
        move_uploaded_file($_FILES['branch_logo']['tmp_name'], $target_path);
    }
}

header("Location: branch_list.php?success=1");
exit;
