#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAX_USERS 100
#define MAX_PUNCHES 100

typedef struct {
    char type[20];
    char time[30];
} Punch;

typedef struct {
    char user_id[20];
    char password[20];
    Punch punches[MAX_PUNCHES];
    int punch_count;
} User;

User users[MAX_USERS];
int user_count = 0;

void load_users() {
    FILE *file = fopen("users.dat", "rb");
    if (file != NULL) {
        fread(&user_count, sizeof(int), 1, file);
        fread(users, sizeof(User), user_count, file);
        fclose(file);
    }
}

void save_users() {
    FILE *file = fopen("users.dat", "wb");
    if (file != NULL) {
        fwrite(&user_count, sizeof(int), 1, file);
        fwrite(users, sizeof(User), user_count, file);
        fclose(file);
    }
}

User* authenticate() {
    char user_id[20];
    char password[20];
    printf("ユーザーIDを入力してください: ");
    scanf("%s", user_id);
    printf("パスワードを入力してください: ");
    scanf("%s", password);

    for (int i = 0; i < user_count; i++) {
        if (strcmp(users[i].user_id, user_id) == 0 && strcmp(users[i].password, password) == 0) {
            printf("ようこそ、%sさん\n", user_id);
            return &users[i];
        }
    }

    printf("認証に失敗しました。\n");
    return NULL;
}

void punch_clock(User *user, const char *punch_type) {
    time_t now = time(NULL);
    struct tm *t = localtime(&now);
    strftime(user->punches[user->punch_count].time, sizeof(user->punches[user->punch_count].time), "%Y-%m-%d %H:%M:%S", t);
    strcpy(user->punches[user->punch_count].type, punch_type);
    user->punch_count++;
    printf("%s打刻: %s\n", punch_type, user->punches[user->punch_count - 1].time);
    save_users();
}

void display_times(User *user) {
    if (user->punch_count == 0) {
        printf("打刻データがありません。\n");
        return;
    }
    for (int i = 0; i < user->punch_count; i++) {
        printf("%s - %s\n", user->punches[i].type, user->punches[i].time);
    }
}

int main() {
    load_users();
    User *user = authenticate();
    if (user == NULL) {
        return 1;
    }

    while (1) {
        int choice;
        printf("\n1. 出勤打刻\n2. 退勤打刻\n3. 休憩開始打刻\n4. 休憩終了打刻\n5. 勤務時間表示\n6. 終了\n");
        printf("選択肢を入力してください: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                punch_clock(user, "出勤");
                break;
            case 2:
                punch_clock(user, "退勤");
                break;
            case 3:
                punch_clock(user, "休憩開始");
                break;
            case 4:
                punch_clock(user, "休憩終了");
                break;
            case 5:
                display_times(user);
                break;
            case 6:
                return 0;
            default:
                printf("無効な選択です。\n");
                break;
        }
    }

    return 0;
}